码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Reverse Linked List II

时间:2015-09-02 01:50:19      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

The basic idea is as follows:

  1. Create a new_head that points to head and use it to locate the immediate node before them-th (notice that it is 1-indexed) node pre;
  2. Set cur to be the immediate node after pre and at each time move the immediate node after cur (named move) to be the immediate node after pre. Repeat it for n - m times.
 1 class Solution {  
 2 public:
 3     ListNode* reverseBetween(ListNode* head, int m, int n) {
 4         ListNode* new_head = new ListNode(0);
 5         new_head -> next = head;
 6         ListNode* pre = new_head;
 7         for (int i = 0; i < m - 1; i++)
 8             pre = pre -> next;
 9         ListNode* cur = pre -> next;
10         for (int i = 0; i < n - m; i++) {
11             ListNode* move = cur -> next; 
12             cur -> next = move -> next;
13             move -> next = pre -> next;
14             pre -> next = move;
15         }
16         return new_head -> next;
17     }
18 };

 

[LeetCode] Reverse Linked List II

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4777400.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!