leetcode/0528_swapping-nodes-in-a-li.../python3/solution.py

26 lines
762 B
Python

# Time: O(N)
# Space: O(1)
class Solution:
def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
# We are using two pointer approach here
kth_node = kth_end_node = None
n = 1
ptr = head
while ptr != None:
if n == k:
kth_node = ptr
# `kth_end_node` ptr will only start moving once
# we've traversed k nodes from the beginning of the
# linked list
if n >= k:
kth_end_node = head if kth_end_node is None else kth_end_node.next
n += 1
ptr = ptr.next
kth_node.val, kth_end_node.val = kth_end_node.val, kth_node.val
return head