Linked List Ops With container/list

Push, move, and remove nodes in container/list so splice operations stay O(1) once you already hold the element pointer.

GoData Integrity

Code

gosnippet
27 lines
package main

import (
	"container/list"
	"fmt"
)

func main() {
	// container/list is a doubly linked list; linked list ops on known nodes are O(1)
	queue := list.New()
	first := queue.PushBack("job-1")
	queue.PushBack("job-2")
	last := queue.PushBack("job-3")

	queue.PushFront("job-0")
	queue.InsertAfter("job-1.5", first) // 已知节点后插入
	queue.MoveToFront(last)             // 已知节点 O(1) 挪位
	queue.Remove(first)

	fmt.Println("length:", queue.Len())
	fmt.Print("order:")
	for element := queue.Front(); element != nil; element = element.Next() {
		fmt.Print(" ", element.Value)
	}
	fmt.Println()
	fmt.Println("front:", queue.Front().Value, "back:", queue.Back().Value)
}

What the code does

Count the function main as the entire surface area of Linked List Ops With container/list.

A single loop drives the file — for element := queue.Front(); element != nil; element = element.Next().

Caveats

  • There is no dependency tree here — the platform is the whole dependency.

Applying it

Running the file prints labeled results such as length:, order:, front: — each operation’s effect is visible in the output.

Statements that decide the outcome

queue.MoveToFront(last)             // 已知节点 O(1) 挪位

Interactive Tools for This Topic

FAQ

What does Linked List Ops With container/list print when run?
No setup needed: run the file and look for labeled lines like `length:`, `order:`, `front:` in the output.