Reverse Linked List II

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->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

 

代码:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *reverseBetween(ListNode *head, int m, int n) {
12         // Start typing your C/C++ solution below
13         // DO NOT write int main() function
14         if (head == NULL) return NULL;
15         if (m == n) return head;
16         
17         ListNode *last = new ListNode(0);
18         last->next = head;
19         
20         ListNode *p1 = head;
21         head = last;
22         for (int i = 1; i < m; ++i)
23         {
24             p1 = p1->next;
25             last = last->next;
26         }
27         
28         ListNode *first = p1;
29         ListNode *p2 = p1->next;
30         ListNode *p3;
31         for (int i = m; i < n; ++i)
32         {
33             p3 = p2->next;
34             p2->next = p1;
35             p1 = p2;
36             p2 = p3;
37         }
38         
39         last->next = p1;
40         first->next = p2;
41         return head->next;
42     }
43 };

 看到有大神给出了神级的代码:

http://discuss.leetcode.com/questions/267/reverse-linked-list-ii

 1 Way 1:
 2 ListNode *reverseBetween(ListNode *head, int m, int n) {
 3     if (!head) return head;
 4     ListNode dummy(0);
 5     dummy.next = head;
 6     ListNode *preM, *prev = &dummy;
 7     for (int i = 1; i <= n; i++) {
 8         if (i <= m) {
 9             if (i == m) preM = prev;
10             prev = head;
11             head = head->next;
12         } else { //m < i <=n
13             prev->next = head->next;
14             head->next = preM->next;
15             preM->next = head;
16             head = prev->next;
17         }
18     }
19     return dummy.next;
20 }
21 
22 Way 2:
23 ListNode *reverseBetween(ListNode *head, int m, int n) {
24     if (!head) return head;
25 
26     ListNode dummy(0);
27     dummy.next = head;
28     ListNode *prev = &dummy;
29     ListNode *curr = head;
30 
31     int i = 0;
32     while (curr && ++i<n) {
33         if (i<m) prev = curr;
34         curr = curr->next;
35     }
36     curr = reverse(prev, curr->next);
37     return dummy.next;
38 }
39 ListNode *reverse(ListNode *begin, ListNode *end)
40 {
41     ListNode *last = begin->next;
42     ListNode *curr = last->next;
43     while (curr != end) {
44         last->next = curr->next;
45         curr->next = begin->next;
46         begin->next = curr;
47         curr = last->next;
48     }
49     return last;
50 }

 

你可能感兴趣的:(list)