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 8dfbf1f

Browse files
authored
Update Swap_Nodes_in_Pairs.py
1 parent 6801df7 commit 8dfbf1f

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

‎Linked_Lists/Swap_Nodes_in_Pairs.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Solution - 1: Time: O(N) and Space: O(1)
1+
# Solution - 1: Swapping the Nodes | Time: O(N) and Space: O(1)
22
class Solution:
33
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
44
# Base condition
@@ -21,3 +21,25 @@ def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
2121
p2 = p1.next
2222

2323
return t_head
24+
25+
26+
# Solution - 2: Swapping the Values | Time: O(N) and Space: O(1)
27+
class Solution:
28+
def swapPairs(self, head: ListNode) -> ListNode:
29+
if not head or not head.next:
30+
return head
31+
p1, p2 = head, head.next
32+
t_head = head
33+
34+
while p1 and p2:
35+
temp = p2.val
36+
p2.val = p1.val
37+
p1.val = temp
38+
39+
if p2.next and p2.next.next:
40+
p1 = p2.next
41+
p2 = p1.next
42+
else:
43+
break
44+
45+
return head

0 commit comments

Comments
(0)

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