Linked List Operations in Go

Lesson Overview

Welcome to our lesson focusing on Linked List Operations in Go. Singly-Linked Lists (or just Linked Lists) are among the most fundamental data structures used in computer science. They provide an efficient way to store and access data that is not necessarily contiguous in memory. This capability distinguishes linked lists from arrays, making them indispensable tools in a programmer's toolkit.

Linked List Definition

A linked list is a linear data structure where each element is a separate object known as a ListNode. In Go, a ListNode is defined using a struct. The struct contains two fields: a value holding the data, and next, which is a pointer to the next ListNode in the linked list. The first element in the list is called the head. Here is how you can define a ListNode struct in Go:

package main

import "fmt"

type ListNode struct {
    value int       // Holds the value or data of the node
    next  *ListNode // Points to the next node in the linked list; default is nil
}

Iterating over a Linked List

The algorithm to iterate over a Linked List in Go is:

  1. Initialize Pointer: Start with a pointer at the head of the list.
  2. Traversal Loop: Use a loop to iterate through the nodes while the current node is not nil.
  3. Process Node: Perform operations on the current node (e.g., print value).
  4. Advance Pointer: Move the pointer to the next node.

Here is the Go code to print out the value of each node:

func main() {
    head := &ListNode{1, 
        &ListNode{2, 
            &ListNode{3,
                &ListNode{4,
                    &ListNode{5, nil}}}}}
                    
    current := head
    for current != nil {
        fmt.Print(current.value, " ")
        current = current.next
    }
    // Prints: 1 2 3 4 5
}

Task Example

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