Skip to content

Instantly share code, notes, and snippets.

@TheAlchemistKE
Created June 6, 2023 18:23
Show Gist options
  • Save TheAlchemistKE/a8550f085fb1b719c9f1a3ed8cf74cbf to your computer and use it in GitHub Desktop.
Save TheAlchemistKE/a8550f085fb1b719c9f1a3ed8cf74cbf to your computer and use it in GitHub Desktop.
package main
import "fmt"
type Node struct {
data interface{}
next *Node
}
type CircularLinkedList struct {
head *Node
}
func (list *CircularLinkedList) IsEmpty() bool {
return list.head == nil
}
func (list *CircularLinkedList) InsertAtHead(data interface{}) {
new := &Node{data: data}
if list.IsEmpty() {
list.head = new
new.next = list.head
} else {
current := list.head
for current.next != list.head {
current = current.next
}
current.next = new
new.next = list.head
list.head = new
}
}
func (list *CircularLinkedList) InsertAtTail(data interface{}) {
new := &Node{data: data}
if list.IsEmpty() {
list.head = new
new.next = list.head
} else {
current := list.head
for current.next != list.head {
current = current.next
}
current.next = new
new.next = list.head
}
}
func (list *CircularLinkedList) Delete(data interface{}) {
if list.IsEmpty() {
fmt.Println("Linked list is empty. No node to delete.")
} else if list.head.data == data {
current := list.head
for current.next != list.head {
current = current.next
}
current.next = list.head.next
list.head = list.head.next
} else {
current := list.head
var prev *Node
for current.next != list.head {
if current.data == data {
prev.next = current.next
return
}
prev = current
current = current.next
}
if current.data == data {
prev.next = list.head
}
}
}
func (list *CircularLinkedList) Display() {
if list.IsEmpty() {
fmt.Println("Linked list is empty.")
} else {
current := list.head
for {
fmt.Print(current.data, " ")
current = current.next
if current == list.head {
break
}
}
fmt.Println()
}
}
// Usage example:
func main() {
linkedList := &CircularLinkedList{}
linkedList.InsertAtHead(5)
linkedList.InsertAtHead(3)
linkedList.InsertAtTail(7)
linkedList.Display() // Output: 3 5 7
linkedList.Delete(3)
linkedList.Display() // Output: 5 7
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment