简体   繁体   English

C++中如何将链表转换为forward_list?

[英]How to convert a linked list into a forward_list in C++?

I have access to the head pointer of a linked list having node structure like this:我可以访问具有如下节点结构的链表的头指针:

struct ListNode {
     int val;
     ListNode *next;
};

For visualization: head ->1->2->3->4->NULL对于可视化: head ->1->2->3->4->NULL

Now, I want to convert this linked list into a C++ forward_list , using the "head" pointer.现在,我想使用“head”指针将此链表转换为 C++ forward_list How do I do it?我该怎么做?

THANKS谢谢

To move the values from your own linked list into a standard forward list is straightforward.将您自己的链表中的值移动到标准正向列表中很简单。 Just walk through your linked list starting at the head, and pass each node value to the push_front method on the resulting forward list.只需从头开始遍历您的链表,并将每个节点值传递给生成的前向列表上的push_front方法。

However, that will produce the forward list in reversed order.但是,这将以相反的顺序生成前向列表。 If you want this to be reversed, then either first reverse the linked list or reverse the forward list after it is populated.如果您希望将其反转,则首先反转链表或在填充后反转正向列表。

To reverse your linked list, see Create a reverse LinkedList in C++ from a given LinkedList .要反转您的链表,请参阅从给定的 LinkedList 在 C++ 中创建反向 LinkedList

To reverse the forward list after the conversion, you can just use the reverse method, which clearly is easier.要在转换反转正向列表,只需使用reverse方法,显然更容易。 So then your function becomes:那么你的 function 变成:

forward_list<int> convert(ListNode *head) {
    forward_list<int> flist;
    while (head != NULL) {
        flist.push_front(head->val);
        head = head->next;
    }
    flist.reverse();
    return flist;
}

You'd call this function like this:你可以这样称呼这个 function :

forward_list<int> flist = convert(head); 

One option is to create an iterator type for your list, wrapping a ListNode* .一种选择是为您的列表创建一个迭代器类型,包装一个ListNode* std::forward_list can be created from any iterator pair. std::forward_list可以从任何迭代器对创建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM