0% found this document useful (0 votes)
33 views2 pages

Java LinkedList Implementation Guide

The document defines a simple implementation of a singly linked list in Java, including methods to add, remove, display, and search for nodes. The LinkedList class manages the nodes, while the Node class represents each element in the list. A demonstration of the linked list operations is provided in the LinkedListDemo class.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views2 pages

Java LinkedList Implementation Guide

The document defines a simple implementation of a singly linked list in Java, including methods to add, remove, display, and search for nodes. The LinkedList class manages the nodes, while the Node class represents each element in the list. A demonstration of the linked list operations is provided in the LinkedListDemo class.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

class Node

{
int data; // Data part
Node next; // Pointer to the next node
// Constructor
Node(int data)
{
[Link] = data;
[Link] = null;
}
}
class LinkedList {
private Node head; // Head of the linked list
// Add a new node to the end of the list
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
}
else
{
Node current = head;
while ([Link] != null)
{
current = [Link];
}
[Link] = newNode;
}
}
public boolean remove(int data)
{
if (head == null)
{
return false; // List is empty
}
if ([Link] == data)
{
head = [Link];
return true;
}
Node current = head;
while ([Link] != null && [Link] != data)
{
current = [Link];
}
if ([Link] == null)
{
return false; // Data not found
}
[Link] = [Link];
return true;
}
public void display()
{
if (head == null)
{
[Link]("List is empty.");
return;
}
Node current = head;
while (current != null)
{
[Link]([Link] + " -> ");
current = [Link];
}
[Link]("null");
}
public boolean search(int data)
{
Node current = head;
while (current != null)
{
if ([Link] == data)
{
return true;
}
current = [Link];
}
return false;
}
}
public class LinkedListDemo
{
public static void main(String[] args)
{
LinkedList list = new LinkedList(); // Adding elements to the list [Link](10);
[Link](20);
[Link](30);
[Link]("Linked List after additions: ");
[Link](); // Removing an element
[Link](20);
[Link]("Linked List after removing 20: ");
[Link]();
boolean found = [Link](30);
[Link]("Is 30 in the list? " + found);
boolean remove = [Link](40);
[Link]("Trying to remove 40: " + (remove ? "Remove" : "Not Found"));
[Link]("Final Linked List: ");
[Link]();
}
}

You might also like