Skip to content

Instantly share code, notes, and snippets.

@TheAlchemistKE
Created June 6, 2023 18:13
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 TheAlchemistKE/3acae631f74372b474f00af9220228a5 to your computer and use it in GitHub Desktop.
Save TheAlchemistKE/3acae631f74372b474f00af9220228a5 to your computer and use it in GitHub Desktop.
package main
import "fmt"
type Node struct {
data interface{}
next *Node
}
type SinglyLinkedList struct {
head *Node
}
func (list *SinglyLinkedList) IsEmpty() bool {
return list.head == nil
}
func (list *SinglyLinkedList) InsertAtHead(data interface{}) {
new := &Node{data: data}
if list.IsEmpty() {
list.head = new
} else {
new.next = list.head
list.head = new
}
}
func (list *SinglyLinkedList) InsertAtTail(data interface{}) {
new := &Node{data: data}
if list.IsEmpty() {
list.head = new
} else {
current := list.head
for current.next != nil {
current = current.next
}
current.next = new
}
}
func (list *SinglyLinkedList) DeleteAtHead() {
if list.IsEmpty() {
fmt.Println("Linked list is empty. No node to delete.")
} else {
list.head = list.head.next
}
}
func (list *SinglyLinkedList) DeleteAtTail() {
if list.IsEmpty() {
fmt.Println("Linked list is empty. No node to delete.")
} else if list.head.next == nil {
list.head = nil
} else {
current := list.head
for current.next.next != nil {
current = current.next
}
current.next = nil
}
}
func (list *SinglyLinkedList) Display() {
if list.IsEmpty() {
fmt.Println("Linked list is empty.")
} else {
current := list.head
for current != nil {
fmt.Print(current.data, " ")
current = current.next
}
fmt.Println()
}
}
// Usage example:
func main() {
linkedList := &SinglyLinkedList{}
linkedList.InsertAtHead(5)
linkedList.InsertAtHead(3)
linkedList.InsertAtTail(7)
linkedList.Display() // Output: 3 5 7
linkedList.DeleteAtHead()
linkedList.DeleteAtTail()
linkedList.Display() // Output: 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment