Singly Linked Lists
Singly Linked Lists
A linked list, in its simplest form, is a collection of nodes that together form a linear ordering. In that each node is an object that stores a reference to an element and a reference, called next, to another node.

Implementing a Singly Linked List
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | /*Node of a single linked list of integer */ public class SinglyLinkedList { private static Node head; /* instance variable */ private static class Node { private int data; /* we assume data integer */ private Node next; /* Create a node with the given data and next node */ public Node(int data) { this.data = data; this.next = null; } } /* Display single list */ public void display() { Node current = head; while (current != null) { System.out.print(current.data + " --> "); current = current.next; } System.out.println("null"); } public static void main(String[] args) { SinglyLinkedList s = new SinglyLinkedList(); s.head = new Node(10); Node second = new Node(7); Node third = new Node(20); Node fourth = new Node(8); s.head.next = second; // 10 --> 7 second.next = third; // 10 -->7 -->20 third.next = fourth; // 10 -->7 --> 20 -->8 -->null System.out.print("Singly Linked List: "); s.display(); } } |
Output:
Singly Linked List: 10 --> 7 --> 20 --> 8 --> null