Skip to content

Instantly share code, notes, and snippets.

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