-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Expand file tree
/
Copy pathswap_in_pairs.py
More file actions
50 lines (39 loc) · 1.11 KB
/
swap_in_pairs.py
File metadata and controls
50 lines (39 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"""
Swap Nodes in Pairs
Given a linked list, swap every two adjacent nodes and return the new head.
Only node links are changed, not node values.
Reference: https://leetcode.com/problems/swap-nodes-in-pairs/
Complexity:
Time: O(n)
Space: O(1)
"""
from __future__ import annotations
class Node:
def __init__(self, x: int) -> None:
self.val = x
self.next: Node | None = None
def swap_pairs(head: Node | None) -> Node | None:
"""Swap every two adjacent nodes in a linked list.
Args:
head: Head of the linked list.
Returns:
The new head after pairwise swapping.
Examples:
>>> a = Node(1); b = Node(2); a.next = b
>>> result = swap_pairs(a)
>>> result.val
2
"""
if not head:
return head
sentinel = Node(0)
sentinel.next = head
current = sentinel
while current.next and current.next.next:
first = current.next
second = current.next.next
first.next = second.next
current.next = second
current.next.next = first
current = current.next.next
return sentinel.next