力扣刷题-热题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.nexth1=hhwhile nex!=tail:h2=h1.nexth1.next=nexnex=h1h1=h2return tail,hhans=ListNode()ans.next=headpre=answhile pre.next:tail=prefor i in range(k):tail=tail.nextif tail==None:return ans.nexta=tail.nextaa,bb=r(pre.next,tail)pre.next=aabb.next=apre=bbreturn 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=ansh=headwhile head:a=[]for i in range(k):if h==None:return ans.nexta.append(h)h=h.nexta.append(h)for i in range(-2,-k-2,-1):pre.next=a[i]pre=pre.nextpre.next=a[-1]return ans.next