Posted on 2023-05-16 20:12
Uriel 阅读(40)
评论(0) 编辑 收藏 引用 所属分类:
数据结构 、
闲来无事重切Leet Code
成对交换单链表的元素,必须通过修改指针实现,参考了Discussion关于self的使用
1 #24
2 #Runtime: 23 ms (Beats 24.1%)
3 #Memory: 13.4 MB (Beats 79.10%)
4
5 # Definition for singly-linked list.
6 # class ListNode(object):
7 # def __init__(self, val=0, next=None):
8 # self.val = val
9 # self.next = next
10 class Solution(object):
11 def swapPairs(self, head):
12 """
13 :type head: ListNode
14 :rtype: ListNode
15 """
16 pre = self
17 pre.next = head
18 while pre.next and pre.next.next:
19 t = pre.next
20 t_next = t.next
21 pre.next, t_next.next, t.next = t_next, t, t_next.next
22 pre = t
23 return self.next