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 7364940

Browse files
author
Suzy Lee
committed
Add leetcode solution 206 in python
1 parent 4921694 commit 7364940

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
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 によって変換されたページ (->オリジナル) /