Working with Doubly-Linked Lists in Go Using the container/list Package

Introduction

Welcome! In this lesson, we'll explore Go's container/list package, an essential part of handling doubly-linked lists in Go. The package provides a ready-to-use doubly-linked list implementation, allowing constant-time insertions and deletions at any point in the sequence. We'll learn how to use this package to perform various operations on doubly-linked lists effectively.

Overview of Doubly-Linked Lists

A doubly-linked list contains nodes that reference both the previous and next nodes in a sequence, allowing for convenient bidirectional traversal. This design strikes a balance between navigation flexibility and the overhead of managing additional pointers.

Working With Go's Linked List

To work with doubly-linked lists in Go, we'll use the container/list package to create an instance of a list. We will then use several useful methods provided:

package main

import (
    "container/list"
    "fmt"
)

func main() {
    students := list.New()

    students.PushBack("John")
    students.PushFront("Alice")
    fmt.Println(students.Front().Value) // prints Alice

    students.Remove(students.Front())
    fmt.Println(students.Front().Value) // prints John
}

In this code, we've established a doubly-linked list called students to store elements. The list is initially empty. Go's container/list package provides several useful methods to manipulate the list:

  • PushBack(): Appends an element to the end of the list and returns the node.
  • PushFront(): Inserts an element at the beginning of the list and returns the node.
  • Remove(): Removes the specified element from the list.

We add "John" to the end and "Alice" to the front. The front element, "Alice", is printed and then removed. Finally, it prints the new front element, "John".

Exploring Linked List Traversal

Traversing a linked list in Go can be achieved using a for loop to visit each element:

func main() {
    students := list.New()

    students.PushBack("John")
    students.PushBack("Alice")

    for e := students.Front(); e != nil; e = e.Next() {
        fmt.Println(e.Value)
    }
    // Output:
    // John
    // Alice
}
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal