File tree Expand file tree Collapse file tree 1 file changed +18
-11
lines changed
Python/chapter02/2.6 - Palindrome Expand file tree Collapse file tree 1 file changed +18
-11
lines changed Original file line number Diff line number Diff line change @@ -56,7 +56,6 @@ def _append_node(self, n: Node) -> None:
56
56
self .tail = self .head
57
57
else :
58
58
end = n
59
- self .tail .next = end
60
59
self .tail = end
61
60
self .size += 1
62
61
@@ -159,22 +158,30 @@ def is_palindrome_constant_space(ll: LinkedList) -> bool:
159
158
"""
160
159
Same as the palindrome function below, but
161
160
with constant space
162
- Runtime: O(n^2 )
161
+ Runtime: O(n)
163
162
Space Complexity: O(1)
164
163
:param ll: an input linked list
165
164
:return: true if ll is a palindrome, false otherwise
166
165
"""
167
- n1 = ll .head
168
- for i in range (math .ceil (ll .size / 2 )):
169
- curr_data = n1 .data
170
- n2 = n1
171
- # advance n2 pointer to desired complement index
172
- for j in range (i , ll .size - i - 1 ):
173
- n2 = n2 .next
174
- # if not the same, then not a palindrome
175
- if n2 .data != curr_data :
166
+ # reverse half of the linked list
167
+ temp_ll1 = LinkedList ()
168
+ temp_ll2 = LinkedList ()
169
+ n = ll .head
170
+ for _ in range (math .ceil (ll .size / 2 )):
171
+ temp_ll1 .append_to_tail (n ) # first half
172
+ n = n .next
173
+ while n is not None :
174
+ temp_ll2 .append_to_tail (n ) # second half
175
+ n = n .next
176
+ temp_ll2 .reverse ()
177
+ # compare temp_ll and ll
178
+ n1 = temp_ll1 .head
179
+ n2 = temp_ll2 .head
180
+ for _ in range (temp_ll2 .size ):
181
+ if n1 .data != n2 .data :
176
182
return False
177
183
n1 = n1 .next
184
+ n2 = n2 .next
178
185
return True
179
186
180
187
You can’t perform that action at this time.
0 commit comments