Implementing Linked List
LINKED LIST IMPLEMENTATION
class SinglyLinkedList1 {
// Node class
private static class Node {
String data;
Node next;
Node(String data) {
this.data = data;
this.next = null;
}
}
Singly Linked List variables
private Node head;
// points to the first node
private Node tail;
// points to the last node
private int size;
// tracks number of nodes
Constructor
public SinglyLinkedList1() {
head = null;
tail = null;
size = 0;
}
To insert an element at the head (beginning) of the list:
// Create a new node containing the new element.
// Set its next reference to the current head node.
// Reassign the head to point to this new node.
// Increase the list size by one.
// Add an element at the beginning of the list
public void addFirst(String data) {
Node newest = new Node(data);
newest.next = head; // link new node to old head
head = newest; // update head to new node
if (tail == null) // if list was empty
tail = newest;
size++;
}
Link
To insert element at Last Steps (Algorithm addLast(e))
// Create a new node containing the element e.
// Set its next reference to null (it will become the last node).
// Set the current tail’s next to this new node (link old tail → new node).
// Update tail to point to this new node.
// Increment size by one.
public void addLast(String data) {
Node newest = new Node(data);
if (head == null) { // if list is empty
head = newest;
tail = newest;
} else {
tail.next = newest;
tail = newest;
}
size++;
}
Link
Tod Delete Element at first -Removing from the Head (Front)
// Move the head pointer to the next node (head = head.next)
// Decrease the list’s size count (size--)
// Remove the first element
public String removeFirst() {
if (head == null) {
System.out.println("List is empty.");
return null;
}
String removedElement = head.data;
head = head.next;
size--;
if (head == null)
tail = null;
return removedElement;
}
Display the list
public void display() {
Node current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}
Main method to test
public static void main(String[] args) {
SinglyLinkedList1 list = new SinglyLinkedList1();
list.addFirst("CHENNAI");
list.display();
list.addFirst("TRICHY");
list.display();
list.addFirst("MADURAI");
list.display();
list.addLast("TIRUNELVELI");
list.display();
list.addFirst("TUTICORIN");
list.removeFirst();
list.display();
System.out.println("Removed: " + list.removeFirst());
list.display();
}
}
OUTPUT
CHENNAI -> null
TRICHY -> CHENNAI -> null
MADURAI -> TRICHY -> CHENNAI -> null
MADURAI -> TRICHY -> CHENNAI -> TIRUNELVELI -> null
MADURAI -> TRICHY -> CHENNAI -> TIRUNELVELI -> null
Removed: MADURAI
TRICHY -> CHENNAI -> TIRUNELVELI -> null
Comments
Post a Comment