Created
June 6, 2023 18:20
-
-
Save TheAlchemistKE/89dd70b802a269a504488754b1e8a4cd to your computer and use it in GitHub Desktop.
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 "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