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 23cdb66

Browse files
Add python solutions to leetcode 24 and 206
1 parent 7364940 commit 23cdb66

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Link: https://leetcode.com/problems/swap-nodes-in-pairs/
2+
3+
######################
4+
# ITERATIVE SOLUTION #
5+
######################
6+
7+
class IterativeSolution:
8+
def swapPairs(self, head: ListNode) -> ListNode:
9+
# EDGE CASE: Linked list has zero or one node
10+
if (head is None) or (head.next is None):
11+
return head
12+
13+
left_node, right_node = head, head.next
14+
15+
# Store the second node as the new head
16+
final_head = right_node
17+
18+
while left_node and right_node:
19+
20+
# Store reference to next left_node
21+
next_left = right_node.next
22+
if next_left:
23+
next_right = right_node.next.next
24+
else:
25+
next_right = None
26+
27+
# Swap the left_node and right_node
28+
right_node.next = left_node
29+
left_node.next = next_right
30+
31+
# If there is an odd number of nodes
32+
if (next_left) and (next_right is None):
33+
left_node.next = next_left
34+
break
35+
36+
# Move onto the next pair of nodes
37+
left_node = next_left
38+
right_node = next_right
39+
40+
return final_head
41+
42+
43+
######################
44+
# RECURSIVE SOLUTION #
45+
######################
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Link to problem: https://leetcode.com/problems/reverse-linked-list/
2+
3+
# Definition for singly-linked list.
4+
# class ListNode:
5+
# def __init__(self, val=0, next=None):
6+
# self.val = val
7+
# self.next = next
8+
class Solution:
9+
10+
def reverseList(self, head: ListNode) -> ListNode:
11+
# Base case: Last node or empty list
12+
if (head is None) or (head.next is None):
13+
return head
14+
15+
# Split up the linked list into two parts:
16+
# 1: first node
17+
# 2: rest of the list
18+
19+
# Let's reverse the rest of the list
20+
rest_list = self.reverseList(head.next);
21+
22+
# Now, let's connect the (reversed) rest of the list
23+
# to the first node. This means the first node now must
24+
# become the last node in the list
25+
head.next.next = head;
26+
head.next = None;
27+
28+
# Make sure you return the rest of the list!
29+
return rest_list;
30+

0 commit comments

Comments
(0)

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