Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 6801df7

Browse files
authored
Create Swap_Nodes_in_Pairs.py
1 parent 8613f07 commit 6801df7

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

‎Linked_Lists/Swap_Nodes_in_Pairs.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Solution - 1: Time: O(N) and Space: O(1)
2+
class Solution:
3+
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
4+
# Base condition
5+
if not head or not head.next:
6+
return head
7+
t_head = head.next
8+
p1, p2 = head, head.next
9+
prev_p1 = None
10+
while p1 and p2:
11+
temp = p2
12+
p1.next = temp.next
13+
temp.next = p1
14+
15+
if prev_p1:
16+
prev_p1.next = p2
17+
prev_p1 = p1
18+
19+
p1 = p1.next
20+
if p1:
21+
p2 = p1.next
22+
23+
return t_head

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /