[面试真题] LeetCode: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->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.

解法:需要定位待翻转部分的头与尾,以及翻转部分相邻的两个节点,同时还要考虑m和n之间的关系。

 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         ListNode *left = new ListNode(0);
15         left->next = head;
16         if(m < 1){
17             return head;
18         }
19         int len = n-m;
20         if(len < 1){
21             return head;
22         }
23         for(int i=1; i<m; i++){
24             left = left->next;
25         }
26         ListNode *phead = left->next;
27         ListNode *pre = left->next;
28         ListNode *lat = pre->next;
29         ListNode *tail = lat->next;
30         while(tail && len-1){
31             lat->next = pre;
32             pre = lat;
33             lat = tail;
34             tail = lat->next;
35             len--;
36         }
37         lat->next = pre;
38         phead->next = tail;
39         left->next = lat;
40         if(m == 1){
41             return left->next;    
42         }else{
43             return head;
44         }
45     }
46 };

Run Status: Accepted!
Program Runtime: 20 milli secs

Progress: 44/44 test cases passed.
posted @ 2013-05-12 17:05  infinityu  阅读(561)  评论(0编辑  收藏  举报