首页 > 其他 > 详细

Reverse Linked List II

时间:2014-03-18 03:14:46      阅读:429      评论: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.

用了栈。注意指针移动时不同指针的分工。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *reverseBetween(ListNode *head, int m, int n) {
        ListNode *guard = new ListNode(0);
        guard -> next =head;
        ListNode *pre = guard;
        ListNode *temp = head;
 
        ListNode *re ;
        stack<ListNode*> sk;
         
         
        for(int i =1 ; i < m ;i++)
        {
            pre = pre->next;
            temp = pre ->next;
        }
        ListNode *tail = temp;
        temp =temp->next;
        for(int i = m ; i < n ; i++)
        {
            sk.push(temp);
            temp =temp->next;
        }
        while(!sk.empty())
        {
            ListNode* tt =sk.top();
            pre->next = tt;
            pre =pre->next;
            sk.pop();
        }
        pre->next = tail;
        tail->next =temp;
        return guard->next;
    }
};

  

Reverse Linked List II,布布扣,bubuko.com

Reverse Linked List II

原文:http://www.cnblogs.com/pengyu2003/p/3605189.html

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