Home > Back-end >  How to convert a linked list into a forward_list in C ?
How to convert a linked list into a forward_list in C ?

Time:12-14

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

Now, I want to convert this linked list into a C forward_list, using the "head" pointer. How do I do it?

THANKS

CodePudding user response:

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.

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.

To reverse the forward list after the conversion, you can just use the reverse method, which clearly is easier. So then your function becomes:

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:

forward_list<int> flist = convert(head); 

CodePudding user response:

One option is to create an iterator type for your list, wrapping a ListNode*. std::forward_list can be created from any iterator pair.

  • Related