Menu
Coddy logo textTech

Recap - Linked List Builder

Part of the Object Oriented Programming section of Coddy's GO journey — lesson 24 of 107.

challenge icon

Challenge

Easy

Let's build a linked list from scratch! You'll create a data structure where each node points to the next, forming a chain of connected values in memory.

You'll organize your code across two files:

  • linkedlist.go: Define a Node struct with Value (int) and Next (*Node) fields. Create a LinkedList struct that holds a pointer to the Head node. Implement these methods on *LinkedList:
    • Append - adds a new node with the given value to the end of the list
    • Prepend - adds a new node with the given value to the beginning of the list
    • Print - traverses the list and prints all values separated by -> , ending with nil
  • main.go: Read values from input, build a linked list by appending and prepending nodes, then print the final list structure.

The following inputs will be provided:

  • Line 1: First value to append
  • Line 2: Second value to append
  • Line 3: Value to prepend

Your Print method should output the list in this format:

[value1] -> [value2] -> [value3] -> nil

For example, given 10, 20, and 5, your output should be:

5 -> 10 -> 20 -> nil

The Append method needs to traverse to the end of the list (where Next is nil) before adding the new node. The Prepend method should create a new node, point its Next to the current head, then update the head to the new node. Remember that an empty list has a nil head, so handle that case in your Append method.

Try it yourself

package main

import "fmt"

func main() {
	// Read input values
	var val1, val2, val3 int
	fmt.Scanln(&val1)
	fmt.Scanln(&val2)
	fmt.Scanln(&val3)

	// Create a new linked list
	list := &LinkedList{}

	// TODO: Use Append to add val1 and val2 to the list

	// TODO: Use Prepend to add val3 to the beginning of the list

	// TODO: Print the final list structure
}

All lessons in Object Oriented Programming