File tree Expand file tree Collapse file tree 2 files changed +57
-0
lines changed Expand file tree Collapse file tree 2 files changed +57
-0
lines changed Original file line number Diff line number Diff line change
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
+
Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments