In Go (Golang), list.New()
is used to create a new doubly linked list. The container/list
package provides the implementation for this data structure. A doubly linked list allows you to store a collection of elements with efficient insertion and removal from both ends or even the middle of the list. Here are some examples of using list.New()
:
Example 1: Basic Usage
This example demonstrates creating a list, adding elements to it, and iterating over it.
package main
import (
"container/list"
"fmt"
)
func main() {
// Create a new linked list
linkedList := list.New()
// Add elements to the list
linkedList.PushBack(1) // Add to the end
linkedList.PushFront(2) // Add to the front
// Iterate over the list and print its elements
for e := linkedList.Front(); e != nil; e = e.Next() {
fmt.Println(e.Value)
}
// Output:
// 2
// 1
}
Example 2: Removing Elements
This example shows how to remove elements from a list.
package main
import (
"container/list"
"fmt"
)
func main() {
// Create a new linked list and add elements
linkedList := list.New()
linkedList.PushBack("a")
linkedList.PushBack("b")
linkedList.PushBack("c")
// Remove the second element ("b")
for e := linkedList.Front(); e != nil; e = e.Next() {
if e.Value == "b" {
linkedList.Remove(e)
break
}
}
// Print the updated list
for e := linkedList.Front(); e != nil; e = e.Next() {
fmt.Println(e.Value)
}
// Output:
// a
// c
}
Example 3: Using a List to Implement a Queue or Stack
A linked list can be used to implement other data structures like a stack.
package main
import (
"container/list"
"fmt"
)
func main() {
stack := list.New()
// Push elements (like stack.push in other languages)
stack.PushBack("world")
stack.PushBack("hello")
// Pop elements (like stack.pop)
for stack.Len() > 0 {
e := stack.Back() // Get the last element
fmt.Println(e.Value)
stack.Remove(e) // Remove the element
}
// Output:
// hello
// world
}
A linked list can be used to implement other data structures like a queue.
package main
import (
"container/list"
"fmt"
)
func main() {
q := list.New()
// Enqueue
q.PushBack("apple")
q.PushBack("banana")
q.PushBack("orange")
for q.Len() > 0 {
// Dequeue
x := q.Front()
q.Remove(x)
fmt.Println(x.Value)
}
// Output:
// apple
// banana
// orange
}
In these examples, PushBack
is used to add elements to the end of the list (which can also act like pushing onto a stack), and PushFront
is used to add elements to the front of the list (useful for queues). The Remove
method deletes an element from the list. You can traverse the list using Front()
and Next()
or Back()
and Prev()
for forward and backward iteration, respectively.