Leetcode-92.翻转链表II

题目链接:https://leetcode-cn.com/problems/reverse-linked-list-ii/

解法1:

1.先找到翻转开始位置,将这位置的前一个结点记录,然后从这个位置到结束位置进行前插创建新链表,将新链表放入原链表中。

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
/**
* 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 *phead=new ListNode(-1);
ListNode *p=head;
ListNode *pfirst=new ListNode(-1);
pfirst->next=head;
if(m==1&&n==1)
return head;
n=n-m;
int i=m;
while(i-->1)
{
pfirst=p;
p=p->next;
}

while(n-->=0)
{
ListNode *temp=p;
p=p->next;
temp->next=phead->next;
phead->next=temp;
}
phead=phead->next;
if(m==1)
head=phead;
else pfirst->next=phead;
while(phead->next!=NULL)
phead=phead->next;
phead->next=p;
return head;
}
};