Reverse K-group linked list
难度:Medium; 类型: linkedlist; 公司:字节研发,华为等
Last updated
难度:Medium; 类型: linkedlist; 公司:字节研发,华为等
Last updated
{1,2,3,4,5},2{2,1,4,3,5}# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
# @param head ListNode类
# @param k int整型
# @return ListNode类
#
class Solution:
def reverseKGroup(self , head , k ):
# write code here
#input: head of linkedlist, k of group size. output: new head of reverse linkedlist
#idea: 用two pointer method
# 物理意义: slow = head, fast = end of sub list
# 由于head会变动,不利于换行更新后的head,所以要加一个fakehead使得fakehead后面的next是新的head
# fast从左往右数计算当前的position% k来看 fast是不是一个size of k的group的end
# if so, reverse slow , fast 之间的sub link list
# then slow = fast, 更新下一个group的head
# base case: head none, return head no reverse
# Time: O(n) for iterate every node, O(k) for reverse group
# so O(kn)
# Space: O(1)
if not head or k <=1:
return head
fake_head = ListNode(None)
fake_head.next = head
slow = fake_head
fast = slow
cnt = 0
while fast:
if cnt!= 0 and cnt%k==0:
# cut sublist
next_head = fast.next
subls_head = slow.next
fast.next = None
new_head, new_tail = self.reverse(slow.next)
# connect
new_tail.next = next_head
slow.next = new_head
# update
fast = new_tail
slow = fast
# update position
fast = fast.next
cnt += 1
return fake_head.next
def reverse(self, node):
prev = None
cur = node
tail = node
while cur:
# backup and reverse
next_node = cur.next
cur.next = prev
# move forward
prev = cur
cur = next_node
new_head= prev
return new_head, tail