Skip to content

Commit 8e77eb3

Browse files
committed
Python soln for Reverse Linked list
1 parent 31ba599 commit 8e77eb3

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
#https://leetcode.com/problems/reverse-linked-list/
2+
3+
# Iterative method
4+
5+
#Approach :
6+
7+
# Store the head in a temp variable called current .
8+
9+
# curr = head , prev = null
10+
11+
# Now for a normal linked list , the current will point to the next node and so on till null
12+
# For reverse linked list, the current node should point to the previous node and the first node here will point to null
13+
14+
# Keep iterating the linkedlist until the last node and keep changing the next of the current node to prev node and also
15+
# update the prev node to current node and current node to next node
16+
17+
18+
# class ListNode:
19+
# def __init__(self, val=0, next=None):
20+
# self.val = val
21+
# self.next = next
22+
23+
class Solution:
24+
25+
def reverseList(self, head):
26+
curr = head
27+
prev = None
28+
while(curr != None):
29+
next = curr.next
30+
curr.next = prev
31+
prev = curr
32+
curr = next
33+
34+
return prev
35+
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Approach :
2+
3+
# Divide the linked list to two halved
4+
# First half is head and the remaining as rest
5+
# The head points to the rest in a normal linked list
6+
# In the reverse linked list , the next of current points to the prev node and the head node should point to NULL
7+
# Keep continuing this process till the last node
8+
9+
10+
# Definition for singly-linked list.
11+
# class ListNode:
12+
# def __init__(self, val=0, next=None):
13+
# self.val = val
14+
# self.next = next
15+
class Solution:
16+
def reverseList(self, head):
17+
if head is None or head.next is None:
18+
return head
19+
rest = self.reverseList(head.next)
20+
head.next.next = head
21+
head.next = None
22+
return rest

0 commit comments

Comments
 (0)