Created
May 30, 2022 20:47
-
-
Save gsrai/2376c1448409b38a11da3670e99e8225 to your computer and use it in GitHub Desktop.
Reverse a Linked List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
type Node[T any] struct { | |
Next *Node[T] | |
Value T | |
} | |
type LinkedList[T any] struct { | |
Head *Node[T] | |
} | |
func NewLinkedList[T any]() *LinkedList[T] { | |
return &LinkedList[T]{} | |
} | |
func (ll *LinkedList[T]) addNode(value T) { | |
n := Node[T]{Next: ll.Head, Value: value} | |
ll.Head = &n | |
} | |
func (ll *LinkedList[T]) String() string { | |
s := " <- head" | |
for element := ll.Head; element != nil; element = element.Next { | |
s = fmt.Sprintf("%v %s", element.Value, s) | |
} | |
return s | |
} | |
func (ll *LinkedList[T]) Reverse() { | |
cn := ll.Head | |
var next, prev *Node[T] | |
for cn != nil { | |
next = cn.Next | |
cn.Next = prev | |
prev = cn | |
cn = next | |
} | |
ll.Head = prev | |
} | |
func main() { | |
ll := NewLinkedList[int]() | |
ll.addNode(1) | |
ll.addNode(2) | |
ll.addNode(3) | |
ll.addNode(4) | |
ll.addNode(5) | |
fmt.Println(ll) | |
ll.Reverse() | |
fmt.Println(ll) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment