给定一个整数单链表,每次反转链表“k”的节点并返回其修改后的列表

2024-09-28 05:19:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我写的输入与预期的输入和输出,我得到的…请解决输入为k=0..我附加的代码在这里

输入1 1. 4 5 7 8 3 36 -1 6. 正确输出1 36 3 8 7 5 4(我得到的)

输入2 1. 4 5 7 8 3 36 -1 0 我没有得到的预期输出 4577836

def kReverse(head, k):
   current = head
   next = None
   prev = None
   count = 0
   while (current is not None and count < k):
       next = current.next
       current.next = prev
       prev = current
       current = next
       count += 1
   if next is not None:
       head.next = kReverse(next, k)
   return prev
    ```

Tags: and代码nonereturnifisdefcount
1条回答
网友
1楼 · 发布于 2024-09-28 05:19:53

此代码不会运行,因为您正在递归地反转k组中的每个节点。但问题是:“如果节点的数量不是k的倍数,那么被忽略的节点最终应该保持不变”

我在leetcode上运行您的代码:这是给定的链接列表:

enter image description here

您正在反转k组中的每个链接列表,并忽略链接列表的最后一部分是否小于k。这是你的结果:

enter image description here

这应该是结果:

enter image description here

以下是我的解决方案:

class Solution:
    def reverse_kth(self,head:ListNode,k:int)->ListNode:
        # create dumy node and point to the head
        dummy=ListNode(0,head)
        group_prev=dummy
        while True:
            kth=self.get_kth(group_prev,k)
            # if I cannot partition the last part, break out of the loop
            if not kth:
                break
            group_next=kth.next
            #reversing the group with two pointer
            # 1-2 -kth   - kth.next  we dont want to break the link
            prev, cur=kth.next,group_prev.next
            while cur!=group_next:
                temp=cur.next
                cur.next=prev
                prev=cur
                cur=temp
            #  this temp is the first node in the group
            temp=group_prev.next
            group_prev.next=kth
            group_prev=temp
        return dummy.next
    # partition the linked list
    def get_kth(self,cur,k):
        while cur and k>0:
            cur=cur.next
            k-=1
        return cur

相关问题 更多 >

    热门问题