@@ -61,11 +61,48 @@ class Solution(object):
61
61
# return prev
62
62
63
63
def reverseList (self , head ):
64
+ """ steps of doing recursion
65
+ 1. define end state and return
66
+ 2. determine where to recurse it in the function
67
+ 3. determine what is the return value for the recursion line
68
+ 4. determine the real func here that helps the recursion works
69
+ """
64
70
# recursion
65
71
# simple recursively without extra space
66
72
if head is None or head .next is None :
67
73
return head
68
- p = self .reverseList (head .next )
69
- head .next .next = head
70
- head .next = None
71
- return p
74
+ new_head = self .reverseList (head .next )
75
+ head .next .next = head # the original next node (head.next) now has a new next, which is the prev one, thus reverse the linked list
76
+ head .next = None # delete the original direction of link
77
+ return new_head # return the new head of the Linked List
78
+
79
+ def reverse_list_with_double_ptr (self , head ):
80
+ # iterative double ptr
81
+ left_ptr , right_ptr = None , head
82
+ while right_ptr :
83
+ temp = right_ptr .next
84
+ right_ptr .next = left_ptr # change the link direction, from left to right to right to left
85
+ # update the ptr position
86
+ left_ptr = right_ptr
87
+ right_ptr = temp
88
+
89
+ return left_ptr # right ptr already None when reaches here, left ptr is the new head
90
+
91
+
92
+
93
+ if __name__ == '__main__' :
94
+ from python .design_linked_list_707 import MyLinkedList
95
+ input_head = [1 , 2 , 3 , 4 , 5 ]
96
+ output_head = [5 , 4 , 3 , 2 , 1 ]
97
+ test_node = ListNode (input_head [0 ])
98
+ test_node .next = ListNode (input_head [1 ])
99
+ input_linked_list = MyLinkedList ()
100
+ for i in range (len (input_head )):
101
+ input_linked_list .addAtIndex (i , input_head [i ])
102
+ solution = Solution ()
103
+ # out = solution.reverseList(input_linked_list.dummy_head)
104
+ out = solution .reverse_list_with_double_ptr (input_linked_list .dummy_head )
105
+ for i in range (len (input_head )):
106
+ val = out .val
107
+ out = out .next
108
+ print (val )
0 commit comments