Sunday, October 25, 2015

Algorithm: reverse the whole liked list

e.g., list=1->2->3->4->null

reverse it to: 4->3->2->1->Null;

-------------------------
1. The procedure is shown below:
using three pointers: cur, pre and tmp. As following example shown, in the first step, put 2 in front of 1, then put 3 in front of 2, ........ until all are reversed. 





2. Note the case when only one node exist. In such a case, "temp = pre->next;" will be wrong! So this line of code should be within the while loop as the codes shown below. 
   


//////////////////////////////////
//code
class Solution {
public:
       ListNode* reorderList(ListNode* head) {

              // reverse the link list
              //ListNode *dum = new ListNode(-1);
              //dum->next = head;
              ListNode* cur = head;
              ListNode* pre = head->next;
             
              cur->next = NULL;//the final node after reverse
              while (pre != NULL)
              {
                     ListNode* temp = pre->next;
                     pre->next = cur;
                     cur = pre;
                     pre = temp;
              }
              head = cur;
              return head;
       }
};

No comments:

Post a Comment