给定这个链表:1->2->3->4->5 当 k = 2 时,应当返回: 2->1->4->3->5 当 k = 3 时,应当返回: 3->2->1->4->5
考察知识点
链表、利用栈先进后出的特点可以做reverse
核心思想
方法一、基于栈
用栈,我们把 k 个数压入栈中,然后弹出来的顺序就是翻转的!
这里要注意几个问题:
第一,剩下的链表个数够不够 k 个(因为不够 k 个不用翻转);
第二,已经翻转的部分要与剩下链表连接起来。
这个方法,不满足只能使用常数的额外空间的要求,故放弃。
方法二、尾插法
锁定 head、cur、tail三个指针,固定尾部,将cur依次插到tail后面。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
pre tail head dummy 12345 # 我们用tail 移到要翻转的部分最后一个元素 pre head tail dummy 12345 cur # 我们尾插法的意思就是,依次把cur移到tail后面 pre tail head dummy 23145 cur # 依次类推 pre tail head dummy 32145 cur ....
classListNode(): def__init__(self, value): self.val = value self.next = None
def__str__(self): returnstr(self.val)
defcreateList(value_list: list) -> ListNode: """ Create Linked List based on list :param value_list: list :return: NodeList """ _len = len(value_list) if _len == 0: returnNone if _len == 1: return ListNode(value_list[0]) else: root = ListNode(value_list[0]) tmp = root for i inrange(1, _len): tmp.next = ListNode(value_list[i]) # 声明当前节点,再把当前节点与前面节点联系在一起。 tmp = tmp.next# 更新tmp return root # 返回根节点
deflistLength(head: ListNode) -> int: """ Get the length of linked list :param head: ListNode :return: int """ count = 0 p = head while p != None: count += 1 p = p.next return count
defconvert2list(head: ListNode) -> list: """ Convert linked list to normal list :param head: ListNonde :return: list """ res = [] p = head while p != None: res.append(p.val) # 由于有ListNode实现了__str__函数 就不用调用p.val来获取节点值了 p = p.next return res
classSolution: defreverseKGroup(self, head: ListNode, k: int) -> ListNode: dummy = ListNode(0) p = dummy whileTrue: count = k stack = [] # 直接调用list做stack,list就有pop函数。 tmp = head # 将head之后的k个node(包括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 head = tmp # 更新head
if __name__ == "__main__": solution = Solution() for i inrange(len(Input)): print("-"*50) result = solution.reverseKGroup(createList(Input[i]), Input1[i]) print(convert2list(result)) print(Answer[i])