Python 每K个节点一组翻转链表 Leetcode No.25
题意: 之前有一道相邻节点之间反转,现在是任意制定k个元素,进行反转。
ps:给初级者的小小建议,当你看不明白我写的文字话,可能是我没写好,也可能是你每有get到我的意思,那么你就尝试变写我的代码,边分析,实在不行就手动模拟一边画图,相信自己可以的。
第一种利用栈结构
首先能想到的当然是通过栈的结构,来进行反转,设置一个栈,先进后出的性质。唯一需要注意的当剩余的元素不足以放到栈里面的时候,就停止反转就好来。
# 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
"""
#用于链接头元素
Phead = ListNode(None)
p = Phead
while True:
count = k
stack = []
tmp = head
while count and tmp:
stack.append(tmp)
tmp = tmp.next
count -= 1
#跳出上面循环的时候,tmp是第k+1的元素来
#如果上面循环结束的时候,count还不为0,那就代表不足k个元素
if count :
p.next = head
break
#对k个元素进行反转
while stack:
p.next = stack.pop()
p = p.next
#与剩下链表链接起来
p.next = tmp
head = tmp
return Phead.next
尾插法
大概思路就是用一个指针指向头节点,一个指向尾部节点,让头节点连接尾部节点所连接的节点。然后让之前头部节点连接的节点,连接头部节点,一直到第一个节点为尾部节点。
eg,1,2,3,4,5,k=3,之前1连接的是2,现在让1,连接4,2之前连接的3,然后让他连接1,3之前连接4,现在连接2,然后让3成为头节点,从4开始往后继续。
# 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
"""
Phead = ListNode(None)
Phead.next, pre ,tail = head, Phead, Phead
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
#当前面都已经反转完毕,就要进行要一个k组的转换,需要更新,pre和tail
#按照k=3的例子,此时pre和tail就指向1这个节点,而我们第一步创建的pre和tail
#指向的是我们自己建立的节点
#感受一下建立一个新的头节点的好处
pre = head
tail= head
return Phead.next
本人最菜的递归
那为什么还要写,还不是为了跳出舒适圈,干就完事。
# 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
"""
cur = head
count = 0
while cur and count != k:
cur = cur.next
count += 1
#通过设置cur,把原先的链表切成几段,每一段在一个递归体里面进行处理。
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