自己1:想采用递归的方式来拼接链表,但是超出了时间限制
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
#解决数量不足的情况
count = 0
temp = head
for i in range(k):
if not temp:
return head
count +=1
temp = temp.next
start = head
res1 = ListNode(-1)
res2 = ListNode(-1)
res1.next = head
count = 0
while True:
if count != k:
temp = ListNode(start.val)
temp.next = res1.next
res1.next = temp
start = start.next
res2.next = start
print(res2.next)
count += 1
else:
break
start.next = self.reverseKGroup(res2.next,k)
return res1
大佬1:利用栈的原理,出栈后天生就是逆序,但是这样做会暂时破坏原有序列之间的连接,不过还是较为简洁的
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseKGroup(self, head, k):
dummy = ListNode(0)
p = dummy
while True:
count = k
stack = []
tmp = head
while count and tmp:
stack.append(tmp)
tmp = tmp.next
count -= 1
# 注意,目前tmp所在k+1位置
# 说明剩下的链表不够k个,跳出循环
if count :
p.next = head
break
# 翻转操作
while stack:
p.next = stack.pop()
p = p.next
#与剩下链表连接起来
p.next = tmp
head = tmp
return dummy.next
大佬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:
cur = head
count = 0
while cur and count!= k: #利用循环来看是否存在k个数据,不满足直接返回
cur = cur.next
count += 1
if count == k:
cur = self.reverseKGroup(cur, k) #循环调用函数
while count: #这个循环内的代码一定要画图看,不然特别容易懵逼,请务必仔细看,贼烧脑,精髓所在。
tmp = head.next
head.next = cur
cur = head
head = tmp
count -= 1
head = cur
return head
大佬3:尾插法
# 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:
dummy = ListNode(0)
dummy.next = head
pre = dummy
tail = dummy
while True:
count = k
while count and tail:
count -= 1
tail = tail.next
if not tail: break
head = pre.next
while pre.next != tail:
cur = pre.next # 获取下一个元素
# pre与cur.next连接起来,此时cur(孤单)掉了出来
pre.next = cur.next
cur.next = tail.next # 和剩余的链表连接起来
tail.next = cur #插在tail后面
# 改变 pre tail 的值
pre = head
tail = head
return dummy.next