Created
May 7, 2021 05:17
-
-
Save kiambogo/72321daafeb3b0d5193bca7828f4acc6 to your computer and use it in GitHub Desktop.
Go Singly 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 "log" | |
type Node struct { | |
val int | |
next *Node | |
} | |
type SinglyLinkedList struct { | |
head *Node | |
} | |
func (sll *SinglyLinkedList) Append(data int) { | |
newNode := &Node{val: data} | |
if sll.head == nil { | |
sll.head = newNode | |
return | |
} | |
ptr := sll.head | |
for ptr.next != nil { | |
ptr = ptr.next | |
} | |
ptr.next = newNode | |
} | |
func (sll *SinglyLinkedList) Delete(d int) { | |
if sll.head == nil { | |
return | |
} | |
ptr := sll.head | |
for ptr.next != nil { | |
if ptr.next.val == d { | |
ptr.next = ptr.next.next | |
return | |
} | |
ptr = ptr.next | |
} | |
} | |
func (sll *SinglyLinkedList) IsEmpty() bool { | |
return sll.head == nil | |
} | |
func main() { | |
sll := &SinglyLinkedList{} | |
assert(true, sll.IsEmpty()) | |
sll.Append(1) | |
sll.Append(2) | |
sll.Append(3) | |
assert(false, sll.IsEmpty()) | |
assert(1, sll.head.val) | |
assert(2, sll.head.next.val) | |
assert(3, sll.head.next.next.val) | |
sll.Delete(2) | |
assert(1, sll.head.val) | |
assert(3, sll.head.next.val) | |
} | |
func assert(expected, actual interface{}) { | |
if expected != actual { | |
log.Panicf("%s != %s", expected, actual) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment