STACK IMPLEMENTATION USING SINGLE LINKED LIST:
import java.util.Scanner;
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public class Stack {
private Node head;
public void insertAtEnd(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
System.out.println(data + " inserted at the end.");
return;
}
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
System.out.println(data + " inserted at the end.");
}
// Deletion at the end
public void deleteAtEnd() {
if(head==null){
System.out.println("List is empty");
return;
}
Node cur = head;
if(cur.next == null){
head = null;
return;
}
Node prev=null;
while(cur.next != null){
prev = cur;
cur = cur.next;
}
prev.next = null;
System.out.println("Data deleted is: "+cur.data);
}
public void display() {
Node current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}
public static void main(String []args) {
PosSll list = new PosSll();
Scanner sc = new Scanner(System.in);
int op, item;
System.out.println("Implementation of Singly Linked List");
while(true) {
System.out.print("1. Insertion at the end 2.Deletion at the end\n
3.Display list\n4.Exit\n");
op = sc.nextInt();
switch(op) {
case 1: System.out.print("Enter value: ");
item = sc.nextInt();
list.insertAtEnd(item);
list.display();
break;
case 2:
list.deleteAtEnd();
list.display();
break;
case 3:
list.display();
break;
case 4:
System.exit(1);
}