码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-04-09 15:16:36      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:没有   node   solution   翻转   int   ret   ini   elf   lse   

示例:

输入: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个节点

标签:没有   node   solution   翻转   int   ret   ini   elf   lse   

原文地址:https://www.cnblogs.com/wenqinchao/p/10676959.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!