Skip to content

Commit 7cd4a58

Browse files
committed
add description
1 parent d5aaa99 commit 7cd4a58

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

Linked List/reverse_linked_list.go

+16
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,19 @@
1+
// Implementation of reversing a linked list recursively and iteratively
2+
/*
3+
In this code, we define a ListNode struct which represents a node in the linked list. We then define two functions:
4+
ReverseListIteratively and ReverseListRecursively which reverse the linked list iteratively and recursively, respectively.
5+
In ReverseListIteratively, we declare two pointers prev and curr, initialize curr to head, and iterate over the
6+
linked list until curr becomes nil. In each iteration, we store the Next pointer of curr in a temporary variable
7+
nextTemp, point curr.Next to prev, update prev to curr, and update curr to nextTemp. Finally, we return prev,
8+
which now points to the new head of the reversed linked list.
9+
10+
In ReverseListRecursively, we first check if head is nil or if head.Next is nil, in which case we return head itself.
11+
Otherwise, we call ReverseListRecursively on head.Next, which returns the new head of the reversed linked list.
12+
We then set head.Next.Next to head and head.Next to nil. Finally, we return the new head.
13+
14+
In the main function, we create a linked list 1 -> 2 -> 3 -> 4 -> 5, reverse it both iteratively and recursively,
15+
and print out the reversed linked lists.
16+
*/
117
package main
218

319
import "fmt"

0 commit comments

Comments
 (0)