翻转链表中第m个节点到第n个节点的部分

样例

例1:

输入: 1->2->3->4->5->NULL, m = 2 and n = 4,
输出: 1->4->3->2->5->NULL.

例2:

输入: 1->2->3->4->NULL, m = 2 and n = 3,
输出: 1->3->2->4->NULL.

挑战

Reverse it in-place and in one-pass

注意事项
m,n满足1 ≤ m ≤ n ≤ 链表长度

源码

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/

class Solution {
public:
/**
* @param head: ListNode head is the head of the linked list
* @param m: An integer
* @param n: An integer
* @return: The head of the reversed ListNode
*/
ListNode * reverseBetween(ListNode * head, int m, int n) {
// write your code here
ListNode * p1,*psre,*pere,*ps,*pe,*penext;

if(m==n)return head;

p1=head;
pe=ps=p1;
if(p1->next!=NULL)
for(int i=1;p1!=NULL;i++,p1=p1->next){
if(i==m){
ps=p1;
}
if(i==n){
pe=p1;
}
if(i<m){
psre=p1;
}
if(i<n){
pere=p1;
}
}

// if(p1->next!=NULL)

penext=pe->next;

if(m!=1)
psre->next=pe;
else{
head=pe;
}

ListNode *tp,*tpnext,*temp;
tp=ps;
if(head->next!=NULL){
tpnext=ps->next;
ps->next=penext;
}

if(n-m!=0){

for(int i=0;i<n-m;i++){
temp=tpnext->next;
tpnext->next=tp;
tp=tpnext;
tpnext=temp;
}
}
return head;
}
};
× 请我吃糖~
打赏二维码