Skip to content

Instantly share code, notes, and snippets.

@P-A-R-U-S
Created May 20, 2019 23:54
Show Gist options
  • Save P-A-R-U-S/55ee88bfecb87f8614e1a4f67b57c866 to your computer and use it in GitHub Desktop.
Save P-A-R-U-S/55ee88bfecb87f8614e1a4f67b57c866 to your computer and use it in GitHub Desktop.
Reverse Linked List in Go/Golang
package Helpers
import (
"testing"
)
type Node struct {
data interface{}
prev *Node
}
type LinkedList struct {
Size int32
head *Node
}
func (list *LinkedList) Add(data int32) {
element := new(Node)
element.data = data
element.prev = list.head
list.head = element
list.Size++
}
func (list *LinkedList) Get(index int32) interface{} {
if list.head == nil {
return 0
}
v := list.head.data
list.head = list.head.prev
list.Size--
return v
}
func (list *LinkedList) List() []interface{} {
if list.head == nil {
return []interface{}{}
}
var result []interface{}
var node = list.head
for node.prev != nil {
result = append(result,node.data)
node = node.prev
}
result = append(result,node.data)
return result
}
func (list *LinkedList) Reverse() {
node := list.head
var prev *Node
for node != nil {
node, prev, node.prev = node.prev, node, prev
}
list.head = prev
}
func (list *LinkedList) IsEmpty() bool {
return list.head == nil
}
func Test_LinkedList(t *testing.T) {
testDatas := []struct{
datas []int32
result []int32
} {
// result in original list and it will be reversed in test
{[]int32{},[]int32{}},
{[]int32{7},[]int32{7}},
{[]int32{0,9,7,6,4,2,1,6},[]int32{6,1,2,4,6,7,9,0}},
{[]int32{3,4,5,6,7},[]int32{7,6,5,4,3}},
}
for _, td := range testDatas {
var i int
var list = LinkedList{}
for _, v := range td.datas {
list.Add(v)
}
var result = list.List()
// Test Original
if len(td.result) != len(result) {
t.Fail()
}
i = len(td.result) -1
for i >= 0 {
if result[i] != td.result[i] {
t.Fail()
}
i--
}
// Test Reversed
for i, j := 0, len(td.result)-1; i < j; i, j = i+1, j-1 {
td.result[i], td.result[j] = td.result[j], td.result[i]
}
list.Reverse()
result = list.List()
if len(td.result) != len(result) {
t.Fail()
}
i = len(td.result) -1
for i >= 0 {
if result[i] != td.result[i] {
t.Fail()
}
i--
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment