Skip to content

Instantly share code, notes, and snippets.

@ympons
Last active March 8, 2016 06:06
Show Gist options
  • Save ympons/66c661689073801d5b4b to your computer and use it in GitHub Desktop.
Save ympons/66c661689073801d5b4b to your computer and use it in GitHub Desktop.
Reverse Linked List
//@ympons
// Reverse Linked List
package main
import "fmt"
type Node struct {
value int
next *Node
}
type List struct {
head *Node
}
func (l *List) Add(v int) {
n := &Node{v, nil}
t := l.head
if (t == nil) {
l.head = n
return
}
for t.next != nil {
t = t.next
}
t.next = n
}
func (l *List) Reverse() {
var prev *Node
current := l.head
var next *Node
for current != nil {
next = current.next
current.next = prev
prev = current
current = next
}
l.head = prev
}
func (l *List) Print() {
t := l.head
for t != nil {
fmt.Println(t.value)
t = t.next
}
}
func main() {
l := List{}
l.Add(1)
l.Add(2)
l.Add(3)
l.Print()
fmt.Println("Reversed")
l.Reverse()
l.Print()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment