You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
if head == None or head.next == None:
return head
l = 1
phead = head
while phead.next:
phead = phead.next
l += 1
p = ListNode(None)
p.next = head
pre = p
cur = p
while l>=k:
cur = pre.next # 1-2-3
for _ in range(k-1):
next = cur.next # 2-3-4
cur.next = next.next # 1-3-4
next.next = pre.next # 2-1-3-4
pre.next = next # None-2-1
pre = cur
l -= k
return p.next
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
示例 :
说明 :
你的算法只能使用常数的额外空间。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
思路:
本题与24题有些相似,需要构建快慢指针完成节点的交换。
由于本题需要将k个节点一组进行翻转,因此最好先通过链表的遍历,确定链表的长度。然后根据链表长度,将链表分为n等份。在每一份中进行局部的翻转,然后将指针指向局部外的节点,进行下一个局部的翻转。直到n等份全部翻转完成,返回头节点。
解法:
The text was updated successfully, but these errors were encountered: