Reversing Linked List - C++

前端 未结 3 1089
既然无缘
既然无缘 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: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;
    }
    

提交回复
热议问题