Lab3 - Data - Staructures and Algorithms

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

SUKKUR IBA UNIVERSITY

Data Structures and Algorithms BE-IV CSE


SPRING 2024

LAB 3

Nama : Zain Ul Abidin CMS:133-22-0001


Understanding Stack Algorithms and Implementation in Java
Objectives
 The objective of this lab is to learn the stack data structure in Java
 The lab is based on algorithms related to stack

Hardware and software required


PC with:
 NetBeans
 Access to internet
 Access to LMS

Theory
A stack is a linear data structure that follows the LIFO (Last–In, First–Out) principle. That
means the objects can be inserted or removed only at one end of it, also called a top.
The stack supports the following operations:
Push: inserts an item at the top of the stack (i.e., above its current top element).
Pop: removes the object at the top of the stack and returns that object from the function. The
stack Size: will be decremented by one.
isEmpty tests if the stack is empty or not.
isFull tests if the stack is full or not.
peek returns the object at the top of the stack without removing it from the stack or modifying
the stack in any way.
size returns the total number of elements present in the stack.

Stack Implementation using an array


A stack can easily be implemented as an array. Following is the stack implementation in Java
using an array:
class Stack
Computer systems engineering department, sukkur iba university 1
{
privateintarr[];
privateint top;
privateint capacity;

// Constructor to initialize the stack


Stack(int size)
{
arr = new int[size];
capacity = size;
top = -1;
}

// Utility function to add an element `x` to the stack


public void push(int x)
{
if (isFull())
{
System.out.println("Overflow\nProgram Terminated\n");
System.exit(-1);
}

System.out.println("Inserting " + x);


arr[++top] = x;
}

// Utility function to pop a top element from the stack


publicint pop()
{
// check for stack underflow
if (isEmpty())
{
System.out.println("Underflow\nProgram Terminated");
System.exit(-1);
}

System.out.println("Removing " + peek());

// decrease stack size by 1 and (optionally) return the popped element


returnarr[top--];
}

// Utility function to return the top element of the stack


publicint peek()
{
if (!isEmpty()) {

Computer systems engineering department, sukkur iba university 2


returnarr[top];
}
else {
System.exit(-1);
}

return -1;
}

// Utility function to return the size of the stack


publicint size() {
return top + 1;
}

// Utility function to check if the stack is empty or not


publicbooleanisEmpty() {
return top == -1; // or return size() == 0;
}

// Utility function to check if the stack is full or not


publicbooleanisFull() {
return top == capacity - 1; // or return size() == capacity;
}
}

class Main
{
public static void main (String[] args)
{
Stack stack = new Stack(3);

stack.push(1); // inserting 1 in the stack


stack.push(2); // inserting 2 in the stack

stack.pop(); // removing the top element (2)


stack.pop(); // removing the top element (1)

stack.push(3); // inserting 3 in the stack

System.out.println("The top element is " + stack.peek());


System.out.println("The stack size is " + stack.size());

stack.pop(); // removing the top element (3)

// check if the stack is empty


if (stack.isEmpty()) {

Computer systems engineering department, sukkur iba university 3


System.out.println("The stack is empty");
}
else {
System.out.println("The stack is not empty");
}
}
}
Output:
Inserting 1
Inserting 2
Removing 2
Removing 1
Inserting 3
The top element is 3
The stack size is 1
Removing 3
The stack is empty
Using Java Collections
importjava.util.Stack;

class Main
{
public static void main(String[] args)
{
Stack<String> stack = new Stack<String>();

stack.push("A"); // Insert `A` into the stack


stack.push("B"); // Insert `B` into the stack
stack.push("C"); // Insert `C` into the stack
stack.push("D"); // Insert `D` into the stack

// prints the top of the stack (`D`)


System.out.println("The top element is " + stack.peek());

stack.pop(); // removing the top element (`D`)


stack.pop(); // removing the next top (`C)

// returns the total number of elements present in the stack


System.out.println("The stack size is " + stack.size());

// check if the stack is empty


if (stack.empty()) {
System.out.println("The stack is empty");
}
else {
System.out.println("The stack is not empty");
Computer systems engineering department, sukkur iba university 4
}
}
}
Output:
The top element is D
The stack size is 2
The stack is not empty
Stack implementation along with Exception Handling
public class Stack {

privateint top;

privateint[] storage;

Stack(int capacity) {

if (capacity <= 0)

throw new IllegalArgumentException(

"Stack's capacity must be positive");

storage = new int[capacity];

top = -1;

void push(int value) {

if (top == storage.length)

throw new StackException("Stack's underlying storage is overflow");

top++;

storage[top] = value;

int peek() {

if (top == -1)

throw new StackException("Stack is empty");

Computer systems engineering department, sukkur iba university 5


return storage[top];

void pop() {

if (top == -1)

throw new StackException("Stack is empty");

top--;

booleanisEmpty() {

return (top == -1);

}
public class StackException extends RuntimeException {

publicStackException(String message) {

super(message);

}
}

}
Reverse a String Using the Stack Data Structure
Approach:
 Insert each character one at a time into the datatype character stack.
 Pop each character from the stack one at a time until the stack is empty.
 Increase the character array by one popped element.
 Create a string from a character array.
 Provide the reversed string.
// using stack data structure a Java Program to Reverse a String
import java.io.*;
importjava.util.*;
classReverseStringUsingStack {
public static String ReverseString(String s)
{
char[] rS = new char[s.length()];
// Declaring an st of Character type
Stack<Character>st = new Stack<Character>();
Computer systems engineering department, sukkur iba university 6
// Traversing the String and pushing the characters of the string
// into the St one by one
for (int j = 0; j <s.length(); j++) {
// pushing the characters into the St
st.push(s.charAt(j));
}
// Now Poping the Characters from the st until
// the st becomes empty
int j = 0;
while (!st.isEmpty()) { // popping elements until from st
// st becomes empty
// getting the character from the top of the st
rS[j++] = st.pop();
}
// returning the string object
return new String(rS);
}
// Main code
public static void main(String args[])
{
String s1 = " SukkurIBA ";
// calling the method
System.out.println(s1 + " <- Reverse -> "
+ ReverseString(s1));
String s2 = " Welcome to SukurIBA ";
// calling the method
System.out.println(s2 + " <- Reverse -> "
+ ReverseString(s2));
}
}
Output:
JavaTpoint<- Reverse ->ABIrukkuS
Welcome to JavaTpoint<- Reverse ->ABIrukkuSotemocleW
Java program to reverse the number Using Stack

importjava.util.Stack;

public class GFG


{
// Stack to maintain order of digits
static Stack<Integer>st= new Stack<>();

// Function to push digits into stack


static void push_digits(int number)

Computer systems engineering department, sukkur iba university 7


{
while(number != 0)
{
st.push(number % 10);
number = number / 10;
}
}

// Function to reverse the number


staticintreverse_number(int number)
{
// Function call to push number's
// digits to stack
push_digits(number);
int reverse = 0;
inti = 1;

// Popping the digits and forming


// the reversed number
while (!st.isEmpty())
{
reverse = reverse + (st.peek() * i);
st.pop();
i = i * 10;
}

// Return the reversed number formed


return reverse;
}

// Driver program to test above function


public static void main(String[] args)
{
int number = 39997;
System.out.println(reverse_number(number));
}
}
Output:
79993
Palindrome check Using Stack
importjava.util.Stack;
importjava.util.Scanner;

Computer systems engineering department, sukkur iba university 8


classPalindromeTest {

public static void main(String[] args) {

System.out.print("Enter any string:");


Scanner in=new Scanner(System.in);
String inputString = in.nextLine();
Stack stack = new Stack();

for (inti = 0; i<inputString.length(); i++) {


stack.push(inputString.charAt(i));
}

String reverseString = "";

while (!stack.isEmpty()) {
reverseString = reverseString+stack.pop();
}

if (inputString.equals(reverseString))
System.out.println("The input String is a palindrome.");
else
System.out.println("The input String is not a palindrome.");

}
}

Output:
Enter any string:abccba
The input String is a palindrome.

Exercise:Do as directed
Task No:01
Write a java program using stack to store the information given in table below so that each
column is stored in a different stack. Later on the program displays the information as it is
givenin the table. Note that the program also helps the user to remove or alter any information
from the table as well.

Computer systems engineering department, sukkur iba university 9


import java.util.Scanner;
import java.util.Stack;

class Lab3Task1 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Create stacks for each column


Stack<String> idStack = new Stack<>();
Stack<String> nameStack = new Stack<>();
Stack<String> classStack = new Stack<>();
Stack<String> markStack = new Stack<>();
Stack<String> genderStack = new Stack<>();

boolean exit = false;

while (!exit) {
System.out.println("\n1. Add Data");
System.out.println("2. Display Table");
System.out.println("3. Remove Data");
System.out.println("4. Alter Data");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");

int choice = scanner.nextInt();


scanner.nextLine(); // Consume the newline

switch (choice) {
case 1:
addData(idStack,nameStack, classStack, markStack,
genderStack, scanner);
break;
case 2:
displayTable(idStack,nameStack, classStack, markStack,
genderStack);

Computer systems engineering department, sukkur iba university 10


break;
case 3:
removeData(idStack,nameStack, classStack, markStack,
genderStack, scanner);
break;
case 4:
alterData(idStack,nameStack, classStack, markStack,
genderStack, scanner);
break;
case 5:
exit = true;
break;
default:
System.out.println("Invalid choice. Please try again.");
break;
}
}

System.out.println("Program terminated.");
scanner.close();
}

private static void addData(Stack<String> idStack,Stack<String> nameStack,


Stack<String> classStack, Stack<String> markStack,Stack<String> genderStack,
Scanner scanner) {
System.out.print("Enter ID: ");
idStack.push(scanner.nextLine());
System.out.print("Enter Name: ");
nameStack.push(scanner.nextLine());
System.out.print("Enter Class: ");
classStack.push(scanner.nextLine());
System.out.print("Enter Mark: ");
markStack.push(scanner.nextLine());
System.out.print("Enter Gender: ");
genderStack.push(scanner.nextLine());
System.out.println("Data added successfully.");
}

private static void displayTable(Stack<String> idStack,Stack<String>


nameStack, Stack<String> classStack, Stack<String> markStack,Stack<String>
genderStack) {
System.out.println("\nTable:");
System.out.println("ID\tName\tClass\tMark\tGender");
for (int i = 0; i < idStack.size(); i++) {
System.out.print(idStack.get(i) + "\t");
System.out.print(nameStack.get(i) + "\t");
System.out.print(classStack.get(i) + "\t");
System.out.print(markStack.get(i) + "\t");
System.out.println(genderStack.get(i));
}
}

private static void removeData(Stack<String> idStack,Stack<String>


nameStack, Stack<String> classStack, Stack<String> markStack,Stack<String>
genderStack, Scanner scanner) {
System.out.print("Enter the index of the data to remove: ");

Computer systems engineering department, sukkur iba university 11


int index = scanner.nextInt();
scanner.nextLine(); // Consume the newline

if (index >= 0 && index < idStack.size()) {


idStack.remove(index);
nameStack.remove(index);
classStack.remove(index);
markStack.remove(index);
genderStack.remove(index);
System.out.println("Data at index " + index + " removed
successfully.");
} else {
System.out.println("Invalid index. Please try again.");
}
}

private static void alterData(Stack<String> idStack,Stack<String>


nameStack, Stack<String> classStack, Stack<String> markStack,Stack<String>
genderStack, Scanner scanner) {
System.out.print("Enter the index of the data to alter: ");
int index = scanner.nextInt();
scanner.nextLine(); // Consume the newline

if (index >= 0 && index < nameStack.size()) {


System.out.print("Enter new ID: ");
idStack.set(index, scanner.nextLine());
System.out.print("Enter new Name: ");
nameStack.set(index, scanner.nextLine());
System.out.print("Enter new Class: ");
classStack.set(index, scanner.nextLine());
System.out.print("Enter new Mark: ");
markStack.set(index, scanner.nextLine());
System.out.print("Enter new Gender: ");
genderStack.set(index, scanner.nextLine());
System.out.println("Data at index " + index + " altered
successfully.");
} else {
System.out.println("Invalid index. Please try again.");
}
}
}

Computer systems engineering department, sukkur iba university 12


Computer systems engineering department, sukkur iba university 13
Computer systems engineering department, sukkur iba university 14
Task No: 02
Modify the program written in task 01 so that whenever an operation is performed on the
stack(s), it throws an exception if a condition is violated.
import java.util.Scanner;
import java.util.Stack;

class Lab3Task2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Create stacks for each column


Stack<String> idStack = new Stack<>();
Stack<String> nameStack = new Stack<>();
Stack<String> classStack = new Stack<>();
Stack<String> markStack = new Stack<>();
Stack<String> genderStack = new Stack<>();

boolean exit = false;


while (!exit) {
System.out.println("\n1. Add Data");
System.out.println("2. Display Table");
System.out.println("3. Remove Data");
System.out.println("4. Alter Data");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");

int choice = scanner.nextInt();


scanner.nextLine(); // Consume the newline
try {
switch (choice) {
case 1:
addData(idStack, nameStack, classStack, markStack,
genderStack, scanner);
break;
case 2:
displayTable(idStack, nameStack, classStack,
markStack, genderStack);
break;
case 3:
removeData(idStack, nameStack, classStack, markStack,
genderStack, scanner);
break;
case 4:
alterData(idStack, nameStack, classStack, markStack,
genderStack, scanner);
break;
case 5:
exit = true;
break;
default:
System.out.println("Invalid choice. Please try
again.");
break;
}

Computer systems engineering department, sukkur iba university 15


} catch (Exception e) {
System.out.println("An error occurred: " + e.getMessage());
}
}

System.out.println("Program terminated.");
scanner.close();
}

private static void addData(Stack<String> idStack, Stack<String>


nameStack, Stack<String> classStack, Stack<String> markStack, Stack<String>
genderStack, Scanner scanner) {
System.out.print("Enter ID: ");
String id = scanner.nextLine();
if (id.isEmpty()) {
throw new IllegalArgumentException("ID cannot be empty.");
}
idStack.push(id);

System.out.print("Enter Name: ");


String name = scanner.nextLine();
if (name.isEmpty()) {
throw new IllegalArgumentException("Name cannot be empty.");
}
nameStack.push(name);

System.out.print("Enter Class: ");


classStack.push(scanner.nextLine());

System.out.print("Enter Mark: ");


markStack.push(scanner.nextLine());

System.out.print("Enter Gender: ");


genderStack.push(scanner.nextLine());

System.out.println("Data added successfully.");


}

private static void displayTable(Stack<String> idStack, Stack<String>


nameStack, Stack<String> classStack, Stack<String> markStack, Stack<String>
genderStack) {
System.out.println("\nTable:");
System.out.println("ID\tName\tClass\tMark\tGender");
for (int i = 0; i < idStack.size(); i++) {
System.out.print(idStack.get(i) + "\t");
System.out.print(nameStack.get(i) + "\t");
System.out.print(classStack.get(i) + "\t");
System.out.print(markStack.get(i) + "\t");
System.out.println(genderStack.get(i));
}
}

private static void removeData(Stack<String> idStack, Stack<String>


nameStack, Stack<String> classStack, Stack<String> markStack, Stack<String>
genderStack, Scanner scanner) {
System.out.print("Enter the index of the data to remove: ");

Computer systems engineering department, sukkur iba university 16


int index = scanner.nextInt();
scanner.nextLine(); // Consume the newline

if (index >= 0 && index < idStack.size()) {


idStack.remove(index);
nameStack.remove(index);
classStack.remove(index);
markStack.remove(index);
genderStack.remove(index);
System.out.println("Data at index " + index + " removed
successfully.");
} else {
throw new IndexOutOfBoundsException("Invalid index. Please try
again.");
}
}

private static void alterData(Stack<String> idStack, Stack<String>


nameStack, Stack<String> classStack, Stack<String> markStack, Stack<String>
genderStack, Scanner scanner) {
System.out.print("Enter the index of the data to alter: ");
int index = scanner.nextInt();
scanner.nextLine(); // Consume the newline

if (index >= 0 && index < nameStack.size()) {


System.out.print("Enter new ID: ");
String id = scanner.nextLine();
if (id.isEmpty()) {
throw new IllegalArgumentException("ID cannot be empty.");
}
idStack.set(index, id);

System.out.print("Enter new Name: ");


String name = scanner.nextLine();
if (name.isEmpty()) {
throw new IllegalArgumentException("Name cannot be empty.");
}
nameStack.set(index, name);

System.out.print("Enter new Class: ");


classStack.set(index, scanner.nextLine());

System.out.print("Enter new Mark: ");


markStack.set(index, scanner.nextLine());

System.out.print("Enter new Gender: ");


genderStack.set(index, scanner.nextLine());

System.out.println("Data at index " + index + " altered


successfully.");
} else {
throw new IndexOutOfBoundsException("Invalid index. Please try
again.");
}
}
}

Computer systems engineering department, sukkur iba university 17


Computer systems engineering department, sukkur iba university 18
Task 03: A letter means push and an asterisk means pop in the following sequence. Give
the sequence of values returned by the pop operations when this sequence of operations is
performed on an initially empty LIFO stack.
EAS*Y*QUE* *ST**IO*N*
Sequence:
import java.util.Stack;

public class Lab3task3 {


public static void main(String[] args) {
String operations = "EAS*Y*QUE**ST**ION*";
Stack<Character> stack = new Stack<>();

for (char operation : operations.toCharArray()) {


if (operation == '*') {
if (!stack.isEmpty()) {
System.out.println("Popped: " + stack.pop());
} else {
System.out.println("Stack is empty. Cannot pop.");
}
} else {
stack.push(operation);
System.out.println("Pushed: " + operation);
}
}
}
}

Computer systems engineering department, sukkur iba university 19

You might also like