Skip to content

Commit 834b0bd

Browse files
committed
add dll in go
1 parent 2f167d7 commit 834b0bd

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

Linked List/double_linked_list.go

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package main
2+
3+
import "fmt"
4+
5+
// Node represents a node in the doubly linked list
6+
type Node struct {
7+
data int
8+
prev *Node
9+
next *Node
10+
}
11+
12+
// LinkedList represents the doubly linked list
13+
type LinkedList struct {
14+
head *Node
15+
tail *Node
16+
}
17+
18+
// AddNode adds a new node to the end of the doubly linked list
19+
func (list *LinkedList) AddNode(data int) {
20+
// Create a new node
21+
newNode := &Node{data: data}
22+
23+
// If the list is empty, set the new node as head and tail
24+
if list.head == nil {
25+
list.head = newNode
26+
list.tail = newNode
27+
return
28+
}
29+
30+
// Set the new node as the next node of the current tail
31+
list.tail.next = newNode
32+
33+
// Set the current tail as the previous node of the new node
34+
newNode.prev = list.tail
35+
36+
// Set the new node as the new tail
37+
list.tail = newNode
38+
}
39+
40+
// PrintList prints the doubly linked list
41+
func (list *LinkedList) PrintList() {
42+
// Start from the head node
43+
currNode := list.head
44+
45+
// Traverse the list and print the data of each node
46+
for currNode != nil {
47+
fmt.Printf("%d ", currNode.data)
48+
currNode = currNode.next
49+
}
50+
}
51+
52+
func main() {
53+
// Create a new doubly linked list
54+
list := &LinkedList{}
55+
56+
// Add nodes to the list
57+
list.AddNode(1)
58+
list.AddNode(2)
59+
list.AddNode(3)
60+
61+
// Print the list
62+
list.PrintList()
63+
}

0 commit comments

Comments
 (0)