In this answer, I have shared how to perform insertion and deletion of data using linked list using Java. A linked list is a linear collection of data elements, whose order is not given by their physical placement in memory. Instead, each element points to the next. It is a data structure consisting of a collection of nodes which together represent a sequence.
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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | /* * Program to perform insertion and deletion of data using linked list in Java */ package com.linkedlist.example; public class NodeApp { public static void main(String[] args) { LinkedListDemo nodeList = new LinkedListDemo(); nodeList.pushNodeAtLast(5); nodeList.pushNodeAtLast(10); nodeList.pushNodeAtLast(20); nodeList.pushNodeAtLast(2); nodeList.pushNodeAtLast(9); nodeList.pushNodeAtAnyPosition(2, 60); nodeList.pushNodeAtLast(90); nodeList.showNode(); nodeList.deleteNodeExceptFirstAndLastNode(900); System.out.println(); nodeList.showNode(); } } package com.linkedlist.example; public class LinkedListDemo { class Node { int data; Node next; public Node(int data) { this.data = data; this.next = null; } } public Node head = null; public Node tail = null; public Node first = null; public Node anyNode = null; public Node temp = null; public void pushNodeAtLast(int item) { Node newNode = new Node(item); if(head == null) { head = newNode; tail = newNode; System.out.println("Data ("+item+") inserted at last"); } else { tail.next = newNode; tail = newNode; System.out.println("Data ("+item+") inserted at last"); } } public void pushNodeAtFirst(int item) { Node firstNode = new Node(item); first = firstNode; first.next = head; head = first; } public void pushNodeAtAnyPosition(int pos, int item) { if(pos == 1) { pushNodeAtFirst(item); } else { Node any = new Node(item); anyNode = any; Node current = head; int counter = 0; while(current != null) { counter++; if(counter == pos-1) { temp = current.next; current.next = anyNode; anyNode.next = temp; break; } current = current.next; } } } public void deleteNodeExceptFirstAndLastNode(int item) { Node current = head; Node temp = current.next; while(current != null && temp != null) { if(temp.data == item) { current.next = temp.next; break; } current = current.next; temp = current.next; if(temp == null) { System.out.println("\n"+"Data("+item+") not found"); } } } public void showNode() { Node current = head; while(current != null) { System.out.print(current.data+" "); current = current.next; } } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.