25. K 个一组翻转链表
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
示例:
给你这个链表:1->2->3->4->5
当 k = 2 时,应当返回: 2->1->4->3->5
当 k = 3 时,应当返回: 3->2->1->4->5
说明:
- 你的算法只能使用常数的额外空间。
- 你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
def swap(pfirst,node_list,plast):
if not pfirst and not plast:
for i in range(len(node_list))[::-1]:
node_list[i].next=node_list[i-1]
node_list[0].next=None
if not pfirst:
for i in range(len(node_list))[::-1]:
node_list[i].next=node_list[i-1]
node_list[0].next=plast
elif not plast:
pfirst.next=node_list[-1]
for i in range(len(node_list))[::-1]:
node_list[i].next=node_list[i-1]
node_list[0].next=None
else:
pfirst.next=node_list[-1]
for i in range(len(node_list))[::-1]:
node_list[i].next=node_list[i-1]
node_list[0].next=plast
node_list=[]
if not head:
return None
pfirst=None
temp=head
for i in range(k):
if temp:
node_list.append(temp)
else:
node_list.append(None)
temp=temp.next
plast=node_list[-1].next if node_list[-1] else None
re=head
if node_list[-1]:
swap(pfirst,node_list,plast)
re=node_list[-1]
pfirst= node_list[0]
temp=pfirst.next if pfirst else None
node_list=[]
for i in range(k):
if temp:
node_list.append(temp)
else:
node_list.append(None)
if temp:
temp=temp.next
plast=node_list[-1].next if node_list[-1] else None
while node_list[-1]:
swap(pfirst,node_list,plast)
pfirst= node_list[0]
temp=pfirst.next if pfirst else None
node_list=[]
for i in range(k):
if temp:
node_list.append(temp)
else:
node_list.append(None)
if temp:
temp=temp.next
plast=node_list[-1].next if node_list[-1] else None
return re
- 这道题问题主要就是要进行实际节点的交换,那么我们写一个交换节点的函数参数就包括要交换的k个节点,他们前面的一个节点跟他们后面的一个节点。(这里需要讨论一下前面的节点为空跟后面的节点为空的情况)
- 接着我们遍历链表,然后每次把k+2个节点存入交换节点的函数,并进行节点的更新即可。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
if head is None or k < 2:
return head
dummy = ListNode(0)
dummy.next = head
start = dummy
end = head
count = 0
while end:
count += 1
if count % k ==0:
start = self.revere(start,end.next)
end = start.next
else:
end = end.next
return dummy.next
def revere(self,start,end):
prev,curr = start,start.next
first = curr
while curr != end:
temp = curr.next
curr.next = prev
prev = curr
curr = temp
start.next = prev
first.next = curr
return first
- 这里对于翻转链表的方式有所改进,即从前往后遍历k歌节点依次将后面的节点加到最前面。