0% found this document useful (0 votes)
33 views

19CSE 212: Data Structures and Algorithms Lab Sheet 5 Stack Adt

The document describes the implementation of a Stack data structure in Java using an array. It provides the code and instructions to: 1. Declare a Stack class with an array and top variable. 2. Add default and parameterized constructors to initialize the array. 3. Implement push(), pop(), peek(), print() and other methods to add/remove elements and view the stack. 4. Include error checking for invalid operations like overflow/underflow. 5. Write test cases and driver code to test the stack implementation.

Uploaded by

Arjun Reddy
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

19CSE 212: Data Structures and Algorithms Lab Sheet 5 Stack Adt

The document describes the implementation of a Stack data structure in Java using an array. It provides the code and instructions to: 1. Declare a Stack class with an array and top variable. 2. Add default and parameterized constructors to initialize the array. 3. Implement push(), pop(), peek(), print() and other methods to add/remove elements and view the stack. 4. Include error checking for invalid operations like overflow/underflow. 5. Write test cases and driver code to test the stack implementation.

Uploaded by

Arjun Reddy
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

19CSE 212: Data structures and Algorithms

Lab sheet 5
STACK ADT

1. Declare a class (StackInt.java) for integer StackInt with two attributes:

(a) An array 'arr' of size 5.

(b) A variable 'top' initialized to -1;

Program:
package com.company;

public class StackInt {

int[] arr=new int[5];


int top;

public StackInt(){
this.top=-1;
}
}

2. Write a separate test driver class (Test.java) and create an object instance of StackInt

class. StackInt si = new StackInt();

Compile both the .java files and run Test.java. Ensure no errors.

Program:
package com.company;

public class Driver {


public static void main(String[] args) {
StackInt si=new StackInt();

System.out.println("Stack top is " + si.top);


}
}

3. Now try to access the 'top' attribute of StackInt from Test.java

directly. System.out.println("Stack top is " + si.top);

Compile and execute.

4. Add a default constructor that will create the stack of some standard top (say 10) in
case user does not give the top.

StackInt() {

arr = new int[10];

top = -1;

Test cases:

StackInt si = new StackInt();

System.out.println(si.arr.length);

Program:
package com.company;

public class StackInt {

int[] arr;
int top;

public StackInt(){
arr=new int[10];
top=-1;

}
}

Output:

5. Add a parameterized constructor that will create the stack with specified

size. StackInt(int sz) {

arr = new int[sz]; top = -1;

Test cases:

StackInt si2 = new StackInt(15);

System.out.println(si2.arr.length);

Program:
package com.company;

public class StackInt {

int[] arr;
int top;

public StackInt(){
arr=new int[10];
top=-1;

public StackInt(int size){


arr=new int[size];
top=-1;
}
}

Output:

4. Add print function to StackInt.java that will print the contents up to the top of the stack. It
should be public.

public void print() {

// Your logic here

// Scan through the array from 0 to top

print the values with tab space in between.

public void print(){


if(top==-1){
System.out.println("Stack Underflow Error");
}else{
System.out.println("Elements in Stack: ");
for(int i=top;i>=0;i--){
System.out.print(arr[i]+" ");
}
System.out.println();
}
}

5. Implement push() method first without checking the array length

limit. public void push(int item) {

// Your logic here

// increment top and set 'top'th position in 'arr' to item

Test cases:

(a) Try invoking push operations and check.

StackInt si = new StackInt();

si.push(100);

si.print();

si.push(200);

si.print();

(b)Try to push beyond stack

capacity StackInt si = new

StackInt();

........................................

si.push(900); si.print(); si.push(300); si.print();

The execution will abort as soon as the last push is invoked.

ArrayIndexOutOfBoundsException.
Program:

public void push(int el){

top++;
arr[top]=el;
}
public class Driver {
public static void main(String[] args) {

StackInt si=new StackInt(3);


si.push(100);
si.print();
si.push(200);
si.print();
si.push(300);
si.print();
si.push(400);
si.print();

}
}

Output:

6. Implement the check to push() method. Don't add an item to the array if top

exceeds arr.length. Instead print "can't push" message.

public void push(int item) {

// Your enhanced logic here

Program:
public void push(int el){

if(top==arr.length-1){
System.out.println("Stack OverFlow Error");
}else{
top++;
arr[top]=el;
}

Output:
(a) Run this time. No exception will be thrown this time around.
7. Add a getter method getTop() which returns the current top of the

stack. public int getTop() {

// return top;

Test cases:

(a) Invoke getTop() from test file and print the top.

System.out.println(si2.getTop());
public int getTop() {

return top;

}
public class Driver {
public static void main(String[] args) {

StackInt si=new StackInt(3);


System.out.println(si.getTop());

Output:

8. Now implement pop() method that removes the topmost item in the stack and returns

it. First without lower bound checking logic.

public int pop() {

// Your logic here

Test cases:

(a) Write push and pop few items to check it’s

working. int item = si.pop();

si.print();

(b) Write pop more items than what were

pushed. int item1 = si.pop();

si.print();

public int pop(){


int item=arr[top];
top--;
return top;
}

public class Driver {


public static void main(String[] args) {

StackInt si=new StackInt(3);


si.push(100);
si.print();
si.push(200);
si.print();
si.push(300);
si.print();

int it1=si.pop();
si.print();
int it2=si.pop();
si.print();
int i3=si.pop();
si.print();
int i4=si.pop();
si.print();

}
}

Output:

The last call to pop should throw Array out of bounds exception.

9. Now implement the check for lower limit (< 0) and print "can't pop"

message. Run test file. Note that no exception will be thrown this time.
public int pop(){

if(top==-1){
System.out.println("Cant Pop (Stack Underflow) ");
return -1;
}

int item=arr[top];
top--;

return top;
}
}

public class Driver {


public static void main(String[] args) {

StackInt si=new StackInt(3);


si.push(100);
si.print();
si.push(200);
si.print();
si.push(300);
si.print();

int it1=si.pop();
si.print();
int it2=si.pop();
si.print();
int i3=si.pop();
si.print();
int i4=si.pop();

}
}

Output:

10. Implement peek() method to return topmost item without removing it from the
stack public int peek() {

// Your logic here

Test cases: (a) Write test file to check the working of peek. This also needs <0 check.

StackInt si = newStackInt[5];

System.out.println(si.peek()); si.push(100);

System.out.println(si.peek()); si.push(200);
System.out.println(si.peek()); si.push(300);

System.out.println(si.peek());

Program:
public int peek(){
if(top==-1){
System.out.println("Cant Peek (Stack Underflow) ");
return -1;
}else{
return arr[top];
}
}

Output:

The first peek() call should print "can't peek" message. Other should return properly.

11. You can't check if contents of two stacks are same by using =

=. Test cases:

StackInt si1 = new

StackInt(); StackInt si2 =

new StackInt();

si1.push(100);

si2.push(100);

si1.push(200);

si2.push(200);

if (si1 == si2)

System.out.println("Both si1 and si2 are same");

else

System.out.println("Both si1 and si2 are not the same");

Run it and check. It will print si1 and si2 are not same. Why?

Because = = operator will only compare 2 addresses. Then how to check the contents?
Output:

12. Implement equals() method which will first compare the top. If not same, return false. If

same, scan through arrays of both stacks to check if each item is one stack is same as an

item in another stack. If so, return true. Else return false.

public boolean equals(Stack another) { // Your logic here }

Test cases:

(a) Now run test file .

It will print si1 and si2 are same since top and contents are same.

Program:
public boolean equal(StackInt s2){
if(this.top==s2.top){

for(int i=this.top;i>=0;i--){
if(this.arr[i]!=s2.arr[i]){
return false;
}
}
return true;
}else{
return false;
}
}

Output:

(b) Now write test file to do same number of pushes but contents

different. StackInt si1 = new StackInt(5);

StackInt si2 = new StackInt(5);

si1.push(100);

si2.push(100);

si1.push(200);

si2.push(300);
if (code)

System.out.println("Both si1 and si2 are same");

else System.out.println("Both si1 and si2 are not the same");

Output:

13. Implement a function getminElement() to return the minimum element in a stack.

Program:
public int getMinElement(){
if(top==-1){
System.out.println("Stack UnderFlow Error");

return -1;
}else{
int min=arr[top];

for(int i=top;i>=0;i--){
if(arr[i]<min){
min=arr[i];
}
}
return min;
}

}
public class Driver {
public static void main(String[] args) {

StackInt si1 = new StackInt(5);


si1.push(10);
si1.push(1);
si1.push(900);
si1.push(878);
si1.push(909);
si1.print();
System.out.println("Minimum element: "+si1.getMinElement());

}
}

Output:
14. Implement a copyStack() function to return a duplicate stack of original stack.

Program:
public StackInt copyStack(){
StackInt duplicate=new StackInt(this.arr.length);

if(this.top==-1){
return duplicate;
}
else {

for (int i = 0; i <= top; i++) {


duplicate.push(this.arr[i]);
}

return duplicate;
}

}
public class Driver {
public static void main(String[] args) {

StackInt si1 = new StackInt(5);


si1.push(10);
si1.push(1);
si1.push(900);
si1.push(878);
si1.push(909);
si1.print();
StackInt duplicateStack=si1.copyStack();
duplicateStack.print();

}
}

Output:

15. Implement a function to reverse an input string using stack.

Program:
package com.company;

import java.util.*;

public class Driver {

static String reverseString(String init){


StackString stack=new StackString(init.length());
char[] finalString =new char[init.length()];

for(int i=0;i<init.length();i++){
stack.push(init.charAt(i));
}

for(int i=0;i<finalString.length;i++){
finalString[i]=stack.pop();
}

return Arrays.toString(finalString);

public static void main(String[] args) {

System.out.println("Enter a String");
Scanner sc=new Scanner(System.in);
String st=sc.nextLine();

System.out.println("Reversed String: "+reverseString(st));

}
}

Output:

16. Given a stack with push(), pop(), empty() operations, delete the middle element in the

stack. Input : Stack[] = [1, 2, 3, 4, 5]

Output : Stack[] = [1, 2, 4, 5]

Input : Stack[] = [1, 2, 3, 4, 5, 6]

Output : Stack[] = [1, 2, 4, 5, 6]

Program:
public void deleteMid(){
if(top==-1){
System.out.println("Stack UnderFlow Error");
}else{

int mid=-1;

mid=(top%2==0)?top/2:(top/2+1);
for(int i=mid;i<=top-1;i++){
arr[i]=arr[i+1];
}

top--;
}
}

Output:

17. Implement a function to sort the elements in a stack.

Program:
public void sortStack(){

if(top==-1){
System.out.println("Stack UnderFlow Error");
}

else {

for (int i = top; i > 0; i--) {


for (int j = top - 1; j >= 0; j--) {
if (arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}

}
public class Driver {

public static void main(String[] args) {

StackInt st=new StackInt(5);


st.push(1);
st.push(32);
st.push(54);
st.push(67);
st.push(100);
System.out.println("Before Sorting: ");
st.print();
st.sortStack();
System.out.println("After Sorting: ");
st.print();

}
}

Output:

18. Implement Two Stacks in a Single Array

Program:
package com.company;

class TwoStacks{
int[] array;
int top1;
int top2;

public TwoStacks(){
array=new int[10];
top1=-1;
top2=array.length;
}

public TwoStacks(int size){


array=new int[size];
top1=-1;
top2=array.length;
}

public void pushStack1(int el){


if((top1)==top2){
System.out.println("Stack-1 OverFlow Error");
}else{
top1++;
array[top1]=el;
}
}

public void pushStack2(int el){


if((top2-1)==top1){
System.out.println("Stack-2 Overflow Error");
}else{
top2--;
array[top2]=el;
}
}

public int pop1Stack1(){


if(top1==-1){
System.out.println("Stack-1 Underflow Error");

return -1;
}else{
int item=array[top1];
top1++;
if(top1==top2){
top1=-1;
}

return item;
}
}

public int pop2Stack2(){


if(top2==array.length){
System.out.println("Stack-2 UnderFloe Error");

return -1;
}else{
int item=array[top2];
top2--;

if(top2==top1){
top2=array.length;
}

return item;
}
}

public void printStack1(){


if(top1==-1){

System.out.println("Cant Print (Stack-1 UndefFlow) ");

}else{
System.out.println("Elements In Stack-1: ");
for(int i=top1;i>=0;i--){
System.out.println(array[i]);
}
}
}

public void printStack2(){


if(top2==array.length){
System.out.println("Cant Print (Stack-2 UnderFlow) ");
}else{
System.out.println("Elements In Stack-2: ");

for(int i=top2;i<array.length;i++){
System.out.println(array[i]);
}
}
}

public class Qn_18 {

public static void main(String[] args) {

TwoStacks st=new TwoStacks(10);

st.pushStack1(10);
st.pushStack1(20);
st.pushStack1(30);
st.pushStack1(40);
st.pushStack1(50);
st.pushStack1(60);
st.pushStack2(100);
st.pushStack2(200);
st.pushStack2(300);
st.pushStack2(400);
st.pushStack2(500);

st.printStack1();
st.printStack2();
}

Output:

Submitted By: Aflah Sedhique

Roll No: AM.EN.U4CSE20105

You might also like