Skip to content

Commit abe29f6

Browse files
committed
add a new reverse-linked-list
1 parent a71618f commit abe29f6

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
"""
2+
https://www.enjoyalgorithms.com/blog/reverse-linked-list
3+
"""
4+
5+
class ListNode:
6+
"""Definition for singly-linked list."""
7+
def __init__(self, val=0, next=None):
8+
self.val = val
9+
self.next = next
10+
11+
12+
def reverse_linked_list(head: ListNode) -> ListNode:
13+
"""
14+
Reverse a singly linked list.
15+
16+
Args:
17+
head: The head node of the linked list.
18+
19+
Returns:
20+
The new head node of the reversed linked list.
21+
22+
Examples:
23+
>>> a = ListNode(1)
24+
>>> b = ListNode(2)
25+
>>> c = ListNode(3)
26+
>>> a.next, b.next = b, c
27+
>>> head = reverse_linked_list(a)
28+
>>> [head.val, head.next.val, head.next.next.val]
29+
[3, 2, 1]
30+
"""
31+
prev = None
32+
current = head
33+
while current:
34+
nxt = current.next
35+
current.next = prev
36+
prev = current
37+
current = nxt
38+
return prev
39+
40+
41+
if __name__ == "__main__":
42+
import doctest
43+
doctest.testmod()
44+
45+
# Example execution
46+
a = ListNode(1)
47+
b = ListNode(2)
48+
c = ListNode(3)
49+
a.next, b.next = b, c
50+
51+
print("Original Linked List: 1 -> 2 -> 3")
52+
new_head = reverse_linked_list(a)
53+
print(f"Reversed Linked List: {new_head.val} -> {new_head.next.val} -> {new_head.next.next.val}")

0 commit comments

Comments
 (0)