首页 > 其他 > 详细

Reverse Linked List II - LeetCode

时间:2015-10-24 12:51:14      阅读:155      评论:0      收藏:0      [点我收藏+]

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.

思路:只要会了reverse k-group,反转链表再也不用愁了呢!

 1 class Solution {
 2 public:
 3     ListNode* reverseBetween(ListNode* head, int m, int n) {
 4         if (head == NULL || m == n) return head;
 5         ListNode prenode(-1);
 6         prenode.next = head;
 7         ListNode *pre = &prenode, *cur, *nex;
 8         int count = m - 1;
 9         while (count && (pre = pre->next))
10             count--;
11         cur = pre->next;
12         nex = cur->next;
13         for (int i = 1; i < n - m + 1; i++)
14         {
15             cur->next = nex->next;
16             nex->next = pre->next;
17             pre->next = nex;
18             nex = cur->next;
19         }
20         return prenode.next;
21     }
22 };

 

Reverse Linked List II - LeetCode

原文:http://www.cnblogs.com/fenshen371/p/4906440.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!