翻转链表中相邻的k个节点

Posted 秦qin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了翻转链表中相邻的k个节点相关的知识,希望对你有一定的参考价值。

示例:

输入:1->2->3->4->5

k=2 输出:2->1->4->3->5

k=3输出:3->2->1->4->5

Python解决方案1:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseKGroup(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if k == 1:
            return head
        
        out_head = ListNode(0)
        out = out_head       
        
        while head:
            i = 0
            part = ListNode(0)
            new = part
            while i < k and head:
                part.next = head
                head = head.next
                part = part.next
                i += 1
                
            if i == k:
                part.next = None
                out.next, last = self.reverse(new.next)
                out = last
            else:
                out.next = new.next
        return out_head.next
    
    def reverse(self,head):
        prev = None
        while head:
            head.next,prev,head = prev,head,head.next
        last = prev
        
        while last.next:
            last = last.next    
        return prev,last

Python解决方案2:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if k == 1:
return head
out = ListNode(1)
out_head = out
while head:
prev = None
i = 0
# 翻转k个相邻的节点
while i < k and head:
head.next,prev,head = prev,head,head.next
if i == 0:
last = prev
i += 1
# 将翻转后的短链表连接到要输出的链表后面
if i == k:
out_head.next = prev
out_head = last
# 最后一次翻转如果没有k个节点,则再翻转一次恢复原来的顺序
else:
re_pre = None
while prev:
prev.next,re_pre,prev = re_pre,prev,prev.next
out_head.next = re_pre
return out.next

以上是关于翻转链表中相邻的k个节点的主要内容,如果未能解决你的问题,请参考以下文章

NC50 链表中的节点每k个一组翻转

leetcode-链表中的节点每k个一组翻转-81

链表中的节点每k个一组翻转

#yyds干货盘点# 面试必刷TOP101:链表中的节点每k个一组翻转

链表中的节点每K个一组翻转(NC50/考察次数Top12/难度中等)

牛客Top200---链表中的节点每k个一组翻转(java通俗易懂详解)