微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决给定一个整数单链表,一次反转链表 'k' 的节点并返回其修改后的列表

我正在编写具有预期输入和输出的输入以及我得到的内容...请解决输入为 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 我没有得到的预期输出 4 5 7 8 3 36

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
    ```

解决方法

此代码将不会运行,因为您正在递归地反转 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。