Thursday, May 9, 2013

Reverse Linked List II(C++)

LeetCode Reverse Linked List II, Jun 27 '121352 / 4252
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 <= m <= n <= length of list.
思路:也没什么特别的,就是要注意考虑边界情况。

  1. ListNode *reverseBetween(ListNode *head, int m, int n) {  
  2.     if(!head) return NULL;  
  3.     if(m == n) return head;  
  4.     ListNode dummy(0);  
  5.     dummy.next = head;  
  6.     ListNode *prev = &dummy;  
  7.     ListNode *first = head;  
  8.     #first's index will be from m to n-1  
  9.     int k = 0;  
  10.     while(k++ < m-1) prev = prev->next;  
  11.     first = prev->next;  
  12.     ListNode *front = first, *back = first->next;  
  13.     for(k = 0; k < n - m; k++){  
  14.        ListNode *temp = back->next;  
  15.        back->next = front;  
  16.        front = back;  
  17.        back = temp;  
  18.     }  
  19.     prev->next = front;  
  20.     first->next = back;  
  21.       
  22.     return dummy.next;  
  23.       
  24.       
  25. }  

No comments:

Post a Comment