1. 题目描述
K 个一组翻转链表:
给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
示例:
给你这个链表:1->2->3->4->5
当 k = 2 时,应当返回: 2->1->4->3->5
当 k = 3 时,应当返回: 3->2->1->4->5
说明:
你的算法只能使用常数的额外空间。
你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
2. 代码实现
方法:利用栈
执行用时 :32 ms, 在所有 Python 提交中击败了92.28%的用户
内存消耗 :14.5 MB, 在所有 Python 提交中击败了8.33%的用户
# 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
"""
# 获得链表长度
current = head
lens = 0
while current:
lens += 1
current = current.next
# 有多少个 k 段要翻转
iters = lens//k
if iters==0:
return head
lisnode = ListNode(-1)
lisno = lisnode
temp = head
stack = []
while iters:
count = k
while count:
stack.append(temp)
temp = temp.next
count -= 1
while stack:
lisno.next = stack.pop()
lisno = lisno.next
lisno.next = temp
iters -= 1
if temp:
lisno.next = temp
return lisnode.next