Reverse Linked List II
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->NULL
, m = 2 and n = 4,
return 1->4->3->2->5->NULL
.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
思路:1, 先判断head是否为空或单节点或m==n,这三种情况都直接返回head即可。
2,需要把m-n之间反转。
2.1, m==1 反转头节点就是head,反转前n-m 个。
2.2, m!=1 先找到反转头节点的前一个节点,把他和反转头节点断开,反转后再连起来
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
//反转链表,但是只反转m-n 之间的
ListNode* inverse(ListNode* head,int k)
{
if(head==NULL||head->next==NULL) return head;;
ListNode*p=head,*q=head->next;
int count=0;
//count计数,反转m-n次就不反转了,一定要循环体内其他语句执行完再count加1
while(q&&count<k)
{
p->next=q->next;
q->next=head;
head=q;
q=p->next;
count++;
}
return head;
}
//这里有很多特殊条件要考虑:1,head或head->next为null;2, m==n,就不用操作了;3, m==1,就不用找反转的头节点了
ListNode *reverseBetween(ListNode *head, int m, int n) {
if(head==NULL||head->next==NULL) return head;
if(m==n)return head;
int k=n-m;
if(m==1)
{
head= inverse(head,k);
return head;
}
//m!=1时,先找到需要反转的头节点的前一个,把他和需要反转的头节点断开,反转后再连上,所以counter==m-1时就取出来
int counter=0;
ListNode*p=head,*tm;
while(p&&counter<m)
{
counter++;
if(counter==(m-1))tm=p;
// if(counter==n)tn=p;
// counter++;
p=p->next; //这里注意先取出p,在令p=p->next;
}
ListNode*h=tm->next;
tm->next==NULL;
h=inverse(h,k);
tm->next=h;
return head;
}
};