力扣刷题-热题100题-第31题(c++、python)
25. K 个一组翻转链表 - 力扣(LeetCode)https://leetcode.cn/problems/reverse-nodes-in-k-group/?envType=study-plan-v2&envId=top-100-liked
常规模拟
根据翻转的长度找到头和尾,进入函数进行翻转
主程序里有循环不断找到头和尾并拼接起来
//c++
/**
* 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:
pair<ListNode*,ListNode*> r(ListNode* head,ListNode* tail)
{
ListNode* pre=tail->next;
ListNode* a=head;
while(pre!=tail)
{
ListNode* nex=a->next;
a->next=pre;
pre=a;
a=nex;
}
return {tail,head};
}
ListNode* reverseKGroup(ListNode* head, int k)
{
ListNode* h=new ListNode(0);
ListNode* pre=h;
h->next=head;
while(head)
{
ListNode* tail=pre;
for(int i=0;i<k;i++)
{
tail=tail->next;
if(!tail) return h->next;
}
ListNode* n=tail->next;
tie(head,tail)=r(head,tail);
pre->next=head;
tail->next=n;
pre=tail;
head=tail->next;
}
return h->next;
}
};
#python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
def r(hh:ListNode,tail:ListNode):
nex=tail.next
h1=hh
while nex!=tail:
h2=h1.next
h1.next=nex
nex=h1
h1=h2
return tail,hh
ans=ListNode()
ans.next=head
pre=ans
while pre.next:
tail=pre
for i in range(k):
tail=tail.next
if tail==None:
return ans.next
a=tail.next
aa,bb=r(pre.next,tail)
pre.next=aa
bb.next=a
pre=bb
return ans.next
这里是我的第一想法,比较愚蠢,直接用内存把地址存起来,然后倒序遍历去拼接,一点参考
#python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
ans=ListNode()
pre=ans
h=head
while head:
a=[]
for i in range(k):
if h==None:
return ans.next
a.append(h)
h=h.next
a.append(h)
for i in range(-2,-k-2,-1):
pre.next=a[i]
pre=pre.next
pre.next=a[-1]
return ans.next