==============================================================================
【id】#25
【title】Reverse Nodes in k-Group
【description】
【idea】
先设置一个dummy head,因为在链表反转时head可能会被改变顺序找不到头节点,所以先用一个假的头节点。
然后找到要反转的k个节点的左右边界l,r。
进行单链表的反转,这里用的非递归算法。
总之是要先将当前节点cur的下一个节点next记录下来,放在tmp,也就是tmp = cur.next ;然后当前节点连接到pre,cur.next = pre;pre的头节点指到cur,pre = cur;cur指向原来的下一个,cur = tmp
【code】
class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
dummy = jump = ListNode(-1)
l = r = dummy.next = head
while True:
# 找到边界
while r.next and count <k:
r = r.next
count += 1
if count == k:
pre,cur = l,r
for _ in range(k):
cur.next, pre, cur = pre, cur, cur.next
# tmp = cur.next
# cur.next = pre
# pre = cur
# cur = tmp
# jump.next = pre
# jump = l
# l = r
jump.next, jump, l = pre,l,r
return dummy.next
【idea】
先把所有的值放在一个list中,然后按照每k个进行反转。最后将新list中的值生成新的链表。
【code】
class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
tmp = []
res = p = ListNode(0)
while head and head.next:
tmp.append(head.val)
head = head.next
for i in range(k,len(tmp),k):
tmp[i: i+k] = tmp[i: i+k][::-1]
for x in tmp:
p.next = ListNode(x)
p = p.next
return res.next