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 72b2994

Browse files
Add recursive solution to leetcode 24
1 parent f300cf7 commit 72b2994

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

‎python_solutions/0024_swap_nodes_in_pairs.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,3 +43,22 @@ def swapPairs(self, head: ListNode) -> ListNode:
4343
######################
4444
# RECURSIVE SOLUTION #
4545
######################
46+
class RecursiveSolution:
47+
def swapPairs(self, head: ListNode) -> ListNode:
48+
# Base case: Undefined node or one node
49+
if (head is None) or (head.next is None):
50+
return head
51+
52+
left_node = head
53+
right_node = head.next
54+
55+
# Figure out the value of left_node for the next recursive call
56+
next_left = None
57+
if (head.next):
58+
next_left = right_node.next
59+
60+
# Swap the positions of the right node and left node
61+
left_node.next = self.swapPairs(next_left)
62+
right_node.next = left_node
63+
64+
return right_node

0 commit comments

Comments
(0)

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