本地IDE VsCode调试链表题(python)
以LeetCode 25. K 个一组翻转链表为例
#定义ListNode()
class ListNode():
def __init__(self, x):
self.val = x
self.next = None
#将传入的数组转化为链表
def create_linked_list(arr):
head = ListNode(arr[0])
cur = head
for i in range(1, len(arr)):
cur.next = ListNode(arr[i])
cur = cur.next
return head
#传入链表头节点,以数组形式返回
def print_linked_list(head):
cur = head
res = []
while cur:
res.append(cur.val)
cur = cur.next
return res
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
dummy = ListNode(0) # 本来在LeetCode写listNode()也行,但这里不可
dummy.next = head
left, right = dummy, head
cnt = 0
while right:
cnt += 1
right = right.next
if cnt % k == 0:
left = self.reverse(left, right)
return dummy.next
def reverse(self, left, right): # left指待反转部分的前一个节点,right指待反转部分的后一个节点
pre, cur = left, left.next
first, last = pre, cur
while cur != right:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
first.next = pre
last.next = right
return last
if __name__ == "__main__":
head = [1,2,3,4,5]
head = create_linked_list(head)
s = Solution()
k = 2
sorted_lists = s.reverseKGroup(head, k)
print(print_linked_list(sorted_lists))
# [2, 1, 4, 3, 5]
个人LeetCode题解(python版本):https://github.com/cielzzz/AlgorithmNotes