File tree Expand file tree Collapse file tree
data_structures/linked_list Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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 } " )
You can’t perform that action at this time.
0 commit comments