Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
35 views3 pages

LAB # 10 Stack ADT Implementation: Object

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 3

Lab#10 Stack ADT Implementation SSUET/QR/114

LAB # 10

Stack ADT Implementation

Object
Implement Stack by using Stack ADT class.

Theory

 Stack is a subclass of Vector that implements a standard last-in, first-out stack.


 Stack only defines the default constructor, which creates an empty stack. Stack includes
all the methods defined by Vector, and adds several of its own.

Public Class Name: Stack

Constructors Object pop( )


Returns the element on the top of the stack, removing
it in the process.
Stack( ) Object push(Object element)
Pushes element onto the stack. Element is also
returned.
Responsibilities int search(Object element)
Searches for element in the stack

boolean empty() Object peek( )


Returns true if the stack is empty, and false Returns the element on the top of the stack, but does
if the stack contains elements. not remove it.

public E push(E item)

Pushes an item onto the top of this stack. This has exactly the same effect as:
addElement(item)

Parameters:
item - the item to be pushed onto this stack.

SWE-203L Data Structure and Algorithms


Lab#10 Stack ADT Implementation SSUET/QR/114

Returns:
the item argument.

public E pop()
Removes the object at the top of this stack and returns that object as the value of this function.

Returns:
The object at the top of this stack (the last item of the Vector object).

Throws:
EmptyStackException - if this stack is empty.

Sample Program#1

import java.util.*;

public class StackDemo {

static void showpush(Stack st, int a) {


st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}

static void showpop(Stack st) {


System.out.print("pop -> ");
Integer a = (Integer) st.pop();
System.out.println(a);
System.out.println("stack: " + st);
}

public static void main(String args[]) {


Stack st = new Stack();
System.out.println("stack: " + st);
showpush(st, 42);
showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);

try {
showpop(st);
} catch (EmptyStackException e) {

SWE-203L Data Structure and Algorithms


Lab#10 Stack ADT Implementation SSUET/QR/114

System.out.println("empty stack");
}
}
}

Lab Task

1. Write a program that takes 20 names as input in stack. Perform all operations on stack
using stack ADT class.

2. Convert the expression from infix to postfix using Stack ADT class.

(A+B) * (C-D)

Home Task

1. Convert and evaluate the expression from infix to postfix using Stack ADT class.

A + ( B * C - ( D / E | F ) * G ) * H

SWE-203L Data Structure and Algorithms

You might also like