LeetCode_Reverse Nodes in k-Group

Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
(链表分组倒排)

Note:

  • Only constant extra memory is allowed.
  • You may not alter the values in the list’s nodes, only nodes itself may be changed.

Example:



1. 链表指针问题(头节点)

遍历链表的过程中保存每 k 个的一组的头尾指针,将其翻转之后继续遍历。具体实现如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def reverse(self, p_prev_head, p_head, p_tail, k):
p = p_head
new_p = ListNode(0)
new_p.next = p_tail.next

while k != 0:
k -= 1
tmp = p.next
p.next = new_p.next
new_p.next = p
p = tmp

p_prev_head.next = new_p.next

def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if k == 1:
return head

new_head = ListNode(0)
new_head.next = head

p_prev_head = new_head
p_head = head
p_tail = head

i = 1
while p_tail != None:
if i == k:
i = 1
self.reverse(p_prev_head, p_head, p_tail, k)
p_prev_head = p_head
p_head = p_prev_head.next
p_tail = p_head
else:
i += 1
p_tail = p_tail.next

return new_head.next