Skip to content

Commit f310525

Browse files
committed
- Reverse Linked List #223
1 parent 3470fbd commit f310525

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

reverse-linked-list/ayosecu.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
from typing import Optional
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+
9+
class Solution:
10+
"""
11+
- Time Complexity: O(n), n = The number of nodes.
12+
- Space Complexity: O(1)
13+
"""
14+
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
15+
pre = None
16+
while head:
17+
nxt = head.next
18+
head.next = pre
19+
pre = head
20+
head = nxt
21+
22+
return pre
23+
24+
def toLinkedList(lists):
25+
dummy = ListNode(-1)
26+
ptr = dummy
27+
for item in lists:
28+
ptr.next = ListNode(item)
29+
ptr = ptr.next
30+
return dummy.next
31+
32+
def toList(head):
33+
result = []
34+
35+
while head:
36+
result.append(head.val)
37+
head = head.next
38+
39+
return result
40+
41+
tc = [
42+
([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]),
43+
([1, 2], [2, 1]),
44+
([], [])
45+
]
46+
47+
sol = Solution()
48+
for i, (l, e) in enumerate(tc, 1):
49+
r = toList(sol.reverseList(toLinkedList(l)))
50+
print(f"TC {i} is Passed!" if r == e else f"TC {i} is Failed! - Expected: {e}, Result: {r}")

0 commit comments

Comments
 (0)