leetcode#92 反转链表II
题目:
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
示例:
输入:head = [1,2,3,4,5], left = 2, right = 4
输出:[1,4,3,2,5]
思路:
1、同反转链表I一样
三个指针pre,now,next,每次把now的指针指向pre,然后三个指针后移一位,最后把整个l,r区间反转一下就可以了。
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
public:
ListNode *reverseBetween(ListNode *head, int left, int right)
{
ListNode *l = head, *r = head, *pre = NULL, *ext = NULL, *now = NULL,*rext=NULL,*lpre=new ListNode(0,head);
ListNode *ans=lpre;
for (int i = 1; i < left; ++i)
if (l)
lpre = l, l = l->next;
for (int i = 1; i < right; ++i)
if (r)
r = r->next,rext=r;
pre = l, now = l ? l->next : NULL, ext = now ? now->next : NULL,rext=r?r->next:NULL;
while(pre!=r)
{
now->next = pre, pre = now, now = ext;
if (ext) ext = ext->next;
}
l->next =rext;
lpre->next = r;
return ans->next;
}
};
2、前插法
因为最开始找到left,right边界需要O(n),反转链表需要O(n),总共需要2*O(n)。有没有一遍遍历就可以的呢,当然有。
对于一个要反转的链表,只要把他的当前节点不断的插入为第一个节点,最后的出的就是反转的链表了。
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
ListNode *dummy=new ListNode(-1,head);
ListNode *pre=dummy,*now=NULL,*ext=NULL;
for(int i=0;i<left-1;++i)
pre=pre->next;
now=ext=pre->next;
for(int i=0;i<right-left;++i)
{
ext=now->next;
now->next=ext->next;
ext->next=pre->next;
pre->next=ext;
}
return dummy->next;
}
};