Reversing Linked List - C++

前端 未结 3 1088
既然无缘
既然无缘 2021-01-17 02:05

I wrote a function that should reverse a list.

So far, I can reverse only two items, but no more. I checked and double checked and still can\'t find the problem. I e

相关标签:
3条回答
  • 2021-01-17 02:18

    Everyone must have the same homework assignment today.

    I think it would be more helpful to these people to show them what happens to the state of the list while it is being reversed. This should help them better than showing them code or code problems.

    Here is what should happen (with the algorithm I would use)

    [] = head () = current

    ([1])->2->3->4, [2]->(1)->3->4, [3]->2->(1)->4, [4]->3->2->(1) done because current now doesn't have a new next

    0 讨论(0)
  • 2021-01-17 02:20

    Sorry for answering late and I am sure that you would have found the answer by now but yet it might be helpful for others. Answer is simply taking return statement (i.e. return head;) out of while loop will fix your problem. Though there are ways you can avoid extra pointer and assignments to optimise your code.

    0 讨论(0)
  • 2021-01-17 02:39

    Your code is close, it is returning early.

    List::ListNode *List::Reverse_List(ListNode *head) 
    {
        ListNode *cur = head;
        ListNode *forward = NULL;
        ListNode *previous = NULL;
    
        while (cur != NULL) {
            //There is no need to use head here, cur will suffice
            //head = cur; //set the head to last node
            forward = cur->next; //save the next pointer in forward
    
            cur->next = previous; //change next to previous
            previous = cur;
            cur = forward;
    
            cout << "cur= " << cur->item << endl; //this is just to display the current value of cur
    
            //don't return here you have only adjusted one node
            //return head;
        }
    
        //at this point cur is NULL, but previous still holds the correct node
        return previous;
    }
    
    0 讨论(0)
提交回复
热议问题