SplDoublyLinkedList
SplDoublyLinkedList implements Iterator, Countable, ArrayAccess, Serializable
The generic SPL doubly-linked list: O(1) push/unshift at both ends, pop/shift from both ends, FIFO/LIFO iteration modes; SplStack/SplQueue are thin subclasses of it.
C C23
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* C in reverse: the doubly-linked list is hand-rolled - nodes with prev/next
plus head/tail pointers make both ends O(1) */
typedef struct Node {
char val[16];
struct Node *prev;
struct Node *next;
} Node;
typedef struct {
Node *head;
Node *tail;
int len;
} List;
static void push_back(List *l, const char *v) {
Node *n = calloc(1, sizeof(Node)); /* zero-initialized node */
strcpy(n->val, v);
n->prev = l->tail;
if (l->tail) {
l->tail->next = n;
} else {
l->head = n;
}
l->tail = n;
l->len++;
}
static void push_front(List *l, const char *v) {
Node *n = calloc(1, sizeof(Node)); /* zero-initialized node */
strcpy(n->val, v);
n->next = l->head;
if (l->head) {
l->head->prev = n;
} else {
l->tail = n;
}
l->head = n;
l->len++;
}
static int pop_back(List *l, char *out) {
if (!l->tail) {
return 0;
}
Node *n = l->tail;
strcpy(out, n->val);
l->tail = n->prev;
if (l->tail) {
l->tail->next = NULL;
} else {
l->head = NULL;
}
free(n);
l->len--;
return 1;
}
static int pop_front(List *l, char *out) {
if (!l->head) {
return 0;
}
Node *n = l->head;
strcpy(out, n->val);
l->head = n->next;
if (l->head) {
l->head->prev = NULL;
} else {
l->tail = NULL;
}
free(n);
l->len--;
return 1;
}
int main(void) {
List l = {NULL, NULL, 0};
char out[16] = {0};
push_back(&l, "tail1");
push_back(&l, "tail2");
push_front(&l, "head1");
printf("top: %s bottom: %s\n", l.tail->val, l.head->val);
pop_back(&l, out);
printf("pop: %s\n", out);
pop_front(&l, out);
printf("shift: %s\n", out);
printf("left:");
for (Node *p = l.head; p; p = p->next) {
printf(" %s", p->val);
}
printf("\n");
return 0;
}
top: tail2 bottom: head1 pop: tail2 shift: head1 left: tail1
C++ C++26
#include <iostream>
#include <list>
#include <string>
int main() {
// C++ in reverse: std::list is the textbook doubly-linked list;
// push_back/push_front and pop_back/pop_front are O(1) at the ends
std::list<std::string> d;
d.push_back("tail1");
d.push_back("tail2");
d.push_front("head1");
std::cout << "top: " << d.back() << " bottom: " << d.front() << "\n";
std::cout << "pop: " << d.back() << "\n";
d.pop_back();
std::cout << "shift: " << d.front() << "\n";
d.pop_front();
std::cout << "left:";
for (const auto &v : d) {
std::cout << " " << v;
}
std::cout << "\n";
return 0;
}
top: tail2 bottom: head1 pop: tail2 shift: head1 left: tail1
C# v11.0.100
using System.Collections.Generic;
// C# in reverse: LinkedList<T> is the doubly-linked list; AddFirst/AddLast
// and RemoveFirst/RemoveLast drive the O(1) ends
var d = new LinkedList<string>();
d.AddLast("tail1");
d.AddLast("tail2");
d.AddFirst("head1");
Console.WriteLine($"top: {d.Last.Value} bottom: {d.First.Value}");
Console.WriteLine("pop: " + d.Last.Value);
d.RemoveLast();
Console.WriteLine("shift: " + d.First.Value);
d.RemoveFirst();
Console.WriteLine("left: [" + string.Join(", ", d) + "]");
top: tail2 bottom: head1 pop: tail2 shift: head1 left: [tail1]
Go v1.27.4
package main
import (
"container/list"
"fmt"
)
// Go in reverse: container/list is the doubly-linked list - PushBack/PushFront
// enter at the ends, Remove(Back())/Remove(Front()) leave at O(1)
func main() {
l := list.New()
l.PushBack("tail1")
l.PushBack("tail2")
l.PushFront("head1")
fmt.Println("top:", l.Back().Value, "bottom:", l.Front().Value)
fmt.Println("pop:", l.Remove(l.Back()))
fmt.Println("shift:", l.Remove(l.Front()))
fmt.Print("left:")
for e := l.Front(); e != nil; e = e.Next() {
fmt.Print(" ", e.Value)
}
fmt.Println()
}
top: tail2 bottom: head1 pop: tail2 shift: head1 left: tail1
Java v27.0.1
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
// Java in reverse: LinkedList is the classic doubly-linked list with
// addLast/addFirst and removeLast/removeFirst at O(1) ends
LinkedList<String> d = new LinkedList<>();
d.addLast("tail1");
d.addLast("tail2");
d.addFirst("head1");
System.out.println("top: " + d.peekLast() + " bottom: " + d.peekFirst());
System.out.println("pop: " + d.removeLast());
System.out.println("shift: " + d.removeFirst());
System.out.println("left: " + d);
}
}
top: tail2 bottom: head1 pop: tail2 shift: head1 left: [tail1]
JavaScript v26.13.1
// JS in reverse: plain arrays already offer push/unshift/pop/shift;
// shift/unshift are O(n) under the hood, heavy loops prefer indexes
const d = [];
d.push("tail1");
d.push("tail2");
d.unshift("head1");
console.log(`top: ${d[d.length - 1]} bottom: ${d[0]}`);
console.log("pop:", d.pop());
console.log("shift:", d.shift());
console.log("left:", d);
top: tail2 bottom: head1 pop: tail2 shift: head1 left: [ 'tail1' ]
PHP v8.6.0
// SplDoublyLinkedList: the generic doubly-linked list under SplStack/SplQueue;
// push/unshift append at the two ends, pop/shift remove from the two ends, all O(1)
$list = new SplDoublyLinkedList();
$list->push("tail1");
$list->push("tail2");
$list->unshift("head1");
echo "top: ", $list->top(), " bottom: ", $list->bottom(), "\n";
echo "pop: ", $list->pop(), "\n";
echo "shift: ", $list->shift(), "\n";
echo "left: ", implode(",", iterator_to_array($list)), "\n";
// Iteration mode: FIFO walks top->bottom (SplQueue-style), LIFO walks bottom->top (SplStack-style)
$list2 = new SplDoublyLinkedList();
$list2->push(1);
$list2->push(2);
$list2->push(3);
$list2->setIteratorMode(SplDoublyLinkedList::IT_MODE_FIFO | SplDoublyLinkedList::IT_MODE_KEEP);
echo "fifo: ", implode(",", iterator_to_array($list2)), "\n";
$list2->setIteratorMode(SplDoublyLinkedList::IT_MODE_LIFO | SplDoublyLinkedList::IT_MODE_KEEP);
echo "lifo: ", implode(",", iterator_to_array($list2)), "\n";
// SplStack and SplQueue are both thin subclasses of this class
echo "SplStack parent: ", get_parent_class(new SplStack());
top: tail2 bottom: head1 pop: tail2 shift: head1 left: tail1 fifo: 1,2,3 lifo: 3,2,1 SplStack parent: SplDoublyLinkedList
Python v3.15.2
# Python in reverse: collections.deque is the two-ended list - append/popleft
# and appendleft/pop are all O(1)
from collections import deque
d = deque()
d.append("tail1")
d.append("tail2")
d.appendleft("head1")
print(f"top: {d[-1]} bottom: {d[0]}")
print("pop:", d.pop())
print("shift:", d.popleft())
print("left:", list(d))
top: tail2 bottom: head1 pop: tail2 shift: head1 left: ['tail1']
Rust v1.99.1
// Rust in reverse: VecDeque is the ring-buffer deque - push_back/push_front
// and pop_back/pop_front are all O(1) at both ends
use std::collections::VecDeque;
fn main() {
let mut d: VecDeque<&str> = VecDeque::new();
d.push_back("tail1");
d.push_back("tail2");
d.push_front("head1");
println!("top: {:?} bottom: {:?}", d.back(), d.front());
println!("pop: {:?}", d.pop_back());
println!("shift: {:?}", d.pop_front());
let left: Vec<&str> = d.iter().copied().collect();
println!("left: {:?}", left);
}
top: Some("tail2") bottom: Some("head1")
pop: Some("tail2")
shift: Some("head1")
left: ["tail1"]
TypeScript v26.13.1
// TS in reverse: type the two-ended array wrapper explicitly - the methods
// are the same push/pop/shift/unshift quartet
const d: string[] = [];
d.push("tail1");
d.push("tail2");
d.unshift("head1");
console.log(`top: ${d[d.length - 1]} bottom: ${d[0]}`);
console.log("pop:", d.pop());
console.log("shift:", d.shift());
console.log("left:", d);
top: tail2 bottom: head1 pop: tail2 shift: head1 left: [ 'tail1' ]
Language differences
C: the doubly-linked list is hand-rolled - nodes with prev/next plus head/tail pointers (shown); O(1) at both ends is entirely on you, and calloc keeps the nodes zero-initialized.
C++: std::list is the textbook doubly-linked list (std::deque is chunked arrays - O(1) ends and cache-friendlier); pick by access pattern.
C#: LinkedList<T> is a bare-node list (poor locality); List<T>/arrays remain the everyday choice - same lesson as PHP: if an array works, skip the list.
Go: container/list is an intrusive doubly-linked list (elements stored as Value any, removal takes the Element pointer back); container/ring covers circular structures.
Java: LinkedList implements Deque as a doubly-linked list; ArrayDeque (circular array) is almost always faster - the Javadoc itself recommends it.
JavaScript: arrays ship the push/pop/shift/unshift quartet; shift/unshift are O(n) - fine for small arrays, big queues want index tricks or hand-rolled ring buffers.
PHP: SplDoublyLinkedList is the GENERIC form of the SPL list: push/unshift enter at the two ends, pop/shift leave from the two ends, all O(1); the iteration mode is a four-way choice FIFO/LIFO x KEEP/DELETE; SplStack/SplQueue are two thin subclasses with preset iteration modes - the "specialized structure vs generic list" split. Note its offsetGet/offsetSet use storage ordinals (from 0), not keys.
Python: collections.deque (C-implemented, chunked) gives O(1) at both ends - the double answer for stack and queue; queue.Queue is the thread-safe variant.
Rust: VecDeque (growable ring buffer) is O(1) at both ends; pure linked nodes are hard to write in Rust thanks to ownership - std::collections::LinkedList exists but its docs say to default away from it.
TypeScript: same as JS - arrays are the container; wrap push/shift when you need explicit two-ended semantics; the O(n) shift rarely matters at web-scale queue lengths.