Linked List
Linked List
JAVA
import java.io.*;
int data;
Node next;
// Constructor
Node(int d)
data = d;
next = null;
// **************INSERTION**************
{
// Create a new node with given data
new_node.next = null;
if (list.head == null) {
list.head = new_node;
else {
last = last.next;
last.next = new_node;
return list;
// **************TRAVERSAL**************
System.out.print("\nLinkedList: ");
// Go to next node
currNode = currNode.next;
System.out.println("\n");
// **************DELETION BY KEY**************
//
// CASE 1:
// If head node itself holds the key to be deleted
return list;
//
// CASE 2:
//
prev = currNode;
currNode = currNode.next;
}
// If the key was present, it should be at currNode
if (currNode != null) {
prev.next = currNode.next;
//
//
if (currNode == null) {
return list;
// **************DELETION AT A POSITION**************
// Method to delete a node in the LinkedList by POSITION
//
// CASE 1:
return list;
//
// CASE 2:
// If the index is greater than 0 but less than the size of LinkedList
//
// The counter
int counter = 0;
// Count for the index to be deleted,
if (counter == index) {
prev.next = currNode.next;
break;
else {
prev = currNode;
currNode = currNode.next;
counter++;
//
// CASE 3: The index is greater than the size of the LinkedList
//
if (currNode == null) {
return list;
// **************MAIN METHOD**************
//
// ******INSERTION******
//
printList(list);
//
// ******DELETION BY KEY******
//
deleteByKey(list, 1);
printList(list);
deleteByKey(list, 4);
printList(list);
// Delete node with value 10
deleteByKey(list, 10);
printList(list);
//
// ******DELETION AT POSITION******
//
deleteAtPosition(list, 0);
printList(list);
deleteAtPosition(list, 2);
printList(list);
deleteAtPosition(list, 10);
printList(list);