Leetcode 1721. Swapping Nodes in a Linked List

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Swapping Nodes in a Linked List

2. Solution

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
def swapNodes(self, head: ListNode, k: int) -> ListNode:
length = 0
ptr = head
while ptr:
length += 1
ptr = ptr.next

ptr = head
count = 0
while ptr:
count += 1
if count == k:
beginning = ptr
if count == length - k + 1
end = ptr
ptr = ptr.next

beginning.val, end.val = end.val, beginning.val
return head
  • Version 2
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def swapNodes(self, head: ListNode, k: int) -> ListNode:
ptr = head
for _ in range(1, k):
ptr = ptr.next

beginning = ptr
end = head
while ptr.next:
ptr = ptr.next
end = end.next
beginning.val, end.val = end.val, beginning.val
return head

Reference

  1. https://leetcode.com/problems/swapping-nodes-in-a-linked-list/
如果有收获,可以请我喝杯咖啡!