A Linked List is a type of linear data structure. It differs from arrays in that elements are not kept in contiguous locations. Instead, Nodes in a linked list are linked using pointers.
Linked List Creation
Structure of a node
There are two parts to each linked list node:
Here,
Data: Data that get stored at a specific location.
Reference: Provides the address of the following linked list node.
Creation & Insertion Operations
Our goal here is to create a java linked list and insert a new node to the end it. For example, we have a Linked List 1→3→5→7→9 and want to add 11 to the end. Adding 11 to the end of the given linked list will update it to 1→3→5→7→9->11.
Code
publicclassInsertNode { classNode { int data; Node next; publicNode(int data) { this.data = data; this.next = null; } } public Node head = null; public Node tail = null; publicvoidaddNode(int data) { System.out.println("Adding a new node with value "+data+" at the end of the linked list "); Node new_Node = new Node(data); if (head == null) { head = new_Node; tail = new_Node; } else { tail.next = new_Node; tail = new_Node; } } publicvoidPrintData() { Node current = head; if (head == null) { System.out.println("Linked List is empty"); return; } while (current != null) { System.out.print(current.data + " "); current = current.next; } System.out.println(); } publicstaticvoidmain(String[] args) { InsertNode List = new InsertNode(); List.addNode(1); List.PrintData(); List.addNode(3); List.PrintData(); List.addNode(5); List.PrintData(); List.addNode(7); List.PrintData(); } }
Output
Adding a new node with value 1 at the end of the linked list 1 Adding a new node with value 3 at the end of the linked list 13 Adding a new node with value 5 at the end of the linked list 135 Adding a new node with value 7 at the end of the linked list 1357