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

[LeetCode92]Reverse Linked List II

时间:2016-03-17 16:02:01      阅读:139      评论: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.

反转m到n处的单链表

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.

分类:Linked List

代码:

class Solution {  
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        ListNode* new_head = new ListNode(0);
        new_head -> next = head;
        ListNode* pre = new_head;
        for (int i = 0; i < m - 1; i++)
            pre = pre -> next;
        ListNode* cur = pre -> next;
        for (int i = 0; i < n - m; i++) {
            ListNode* move = cur -> next; 
            cur -> next = move -> next;
            move -> next = pre -> next;
            pre -> next = move;
        }
        return new_head -> next;
    }
}; 

 

[LeetCode92]Reverse Linked List II

标签:

原文地址:http://www.cnblogs.com/zhangbaochong/p/5287562.html

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