Skip to content

Instantly share code, notes, and snippets.

@sagar290
Created September 3, 2022 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sagar290/56262583b2f44976c92bea122d04dc4e to your computer and use it in GitHub Desktop.
Save sagar290/56262583b2f44976c92bea122d04dc4e to your computer and use it in GitHub Desktop.
Linked List in go
package main
import "fmt"
type node struct {
data int
next *node
}
type linkedList struct {
head *node
length int
}
func (l *linkedList) prepend(n *node) {
second := l.head
l.head = n
l.head.next = second
l.length++
}
func (l linkedList) printList() {
toPoint := l.head
for l.length != 0 {
fmt.Printf("%d ", toPoint.data)
toPoint = toPoint.next
l.length--
}
fmt.Print("\n")
}
func (l *linkedList) deleteWithValue(value int) {
if l.length == 0 {
return
}
if l.head.data == value {
l.head = l.head.next
l.length--
return
}
previousToDelete := l.head
for previousToDelete.next.data != value {
if previousToDelete.next.next == nil {
return
}
previousToDelete = previousToDelete.next
}
previousToDelete.next = previousToDelete.next.next
l.length--
}
func main() {
mylist := linkedList{}
node1 := &node{data: 48}
node2 := &node{data: 16}
node3 := &node{data: 17}
node4 := &node{data: 157}
node5 := &node{data: 156}
node6 := &node{data: 1534}
node7 := &node{data: 15232}
mylist.prepend(node1)
mylist.prepend(node2)
mylist.prepend(node3)
mylist.prepend(node4)
mylist.prepend(node5)
mylist.prepend(node6)
mylist.prepend(node7)
fmt.Println(mylist)
mylist.printList()
mylist.deleteWithValue(17)
mylist.printList()
mylist.deleteWithValue(17)
mylist.printList()
mylist.deleteWithValue(15232)
mylist.printList()
mylist.deleteWithValue(48)
mylist.printList()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment