data-structures

Definition

Ring List

A ring list is a special for of a linked list where all nodes are connected to form a circle. Unlike a regular linked list, which ends with a node pointing to null, the last node points back to the first node.

Implementations

Java Implementation

public class RingList<T> {
    private class Node {
        T data;
        Node next;
 
        private Node(T data, Node next) {
            this.data = data;
            this.next = next;
        }
    }
 
    private Node nil = new Node(null, null);
 
    public RingList() {
        this.nil.next = this.nil;
    }
 
    public T poll() {
        Node n = nil.next;
        this.nil.next = n.next;
        return n.data;
    }
 
    public void add(T data) {
        nil.data = data;
        nil.next = (nil = new Node(null, nil.next));
    }
 
    public void print() {
        Node n = nil.next;
        while (n != nil) {
            System.out.print(n.data + " ");
            n = n.next;
        }
        System.out.println();
    }
}