文章作者:Tyan 博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
- Version 1
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
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
- https://leetcode.com/problems/swapping-nodes-in-a-linked-list/