题目:K 个一组翻转链表
思想:
遍历链表,计数k个后,记住K个结点的首尾节点传递给反转函数,返回反转后链表的首尾结点,再拼接到原来的链表.
class Solution:
def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
count = 0
result = ListNode()
result.next = head
# 首尾结点
first = result
second = head
if k == 1:
return result.next
while second !=None and first !=None:
second = second.next
count = count + 1
if count == k:
# k个结点的链表反转
lhead,lend= self.ReverseList(first.next, second)
# 反转后的链表拼接到原链表
first.next = lhead
lend.next = second
# 继续下一组k个结点
first = lend
count = 0
return result.next
# 反转链表
def ReverseList(self, head, end):
if not head or not head.next:
return head
cur = head
last = None
# 当cur为空时,last指向了最后一个节点
while True:
#先用tmp保存cur的下一个节点的信息,
tmp = cur.next
# 改变指向前一个节点
cur.next = last
#让last,cur依次向后移动一个节点,继续下一次的指针反转
last = cur
cur = tmp
if cur == end:
break
return last, head