翻转链表中的一部分

要求

翻转链表的第m到第n部分,例如:1->2->3->4->5->NULL,m=2,n=4,返回1->4->3->2->5->NULL

代码实现

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
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
using namespace::std;


struct ListNode {
      int val;
      ListNode *next;
      ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:


    ListNode* reverseBetween(ListNode* head, int m, int n) {
        if (head==NULL||head->next==NULL) {
            return head;
        }else if (m==n){
            return head;
        }else{
            ListNode* newHead = new ListNode(0);
            newHead->next = head;

            //first为第m-1个结点
            ListNode* first = newHead;
            for (int i=1; i<m; i++) {
                first = first->next;
            }


            ListNode* pre = first->next;
            ListNode* p = pre->next;
            ListNode* next = NULL;

            //top为第m个结点,也是翻转部分翻转后的尾结点
            ListNode* top = pre;
            for (int i =m; i<n; i++) {
                next = p->next;
                p->next = pre;
                pre = p;
                p = next;
            }
            //这时候p为第n+1个结点,pre为翻转部分翻转后的头结点

            top->next = p;
            first->next = pre;

            return newHead->next;
        }
    }
};
int main(int argc, const char * argv[]) {
    // insert code here...
    std::cout << "Hello, World!\n";
    return 0;
}

Comments