• No results found

lecture-7-ADTstack-2011-1 (2).pdf

N/A
N/A
Protected

Academic year: 2020

Share "lecture-7-ADTstack-2011-1 (2).pdf"

Copied!
39
0
0

Loading.... (view fulltext now)

Full text

(1)

STACK ADT

Def: a stack, is a list of items (objects) in which entries are added and removed from one end called the top of the stack • Logical view :

• Top of stack

• The top element is the last element added to the stack. And it is the first element to be removed. So this structure called LIFO structure (LAST-IN-LAST-OUT).

D

C

(2)

Applications and implementations

• applications in stack

– compiler and OS design.

– Math expression evaluation: (testing the balanced

expressions, evaluation of expressions, converting

expressions).

– calling and returning functions

– checking palindrome strings……

• implementations used:

– A linked implementation.

(3)

Abstract Data Type Stack specification

Data

– A collection of objects in a specific order

Operations

- push(newEntry) Task: Adds a new entry to the top of the stack.

Input: newEntry is the new entry as object to be pushed. Output: None.

- pop() Task: Removes and returns the top of the stack. Input: None.

Output: Returns either the top of the stack or null if the stack was empty.

-peek() Task: retrieves the top of the stack without changing the stack state in any way

Input: None.

(4)

Abstract Data Type Stack specification

- isEmpty() Task: Determines whether the stack is empty. Input: None.

Output: Returns true if the stack is empty. - Clear() Task: Removes all entries from the stack. Input: None.

Output: None. Note: Alternate names for methods

– add – remove – insert – delete

– pull mean pop,

(5)

STACK INTERFACE

Public Interface StackInterface{

/** Task: Adds a new entry to the top of the stack.

*@param newEntry an object to be added to the stack*/

public Void push(Object newEntry);

/** Task: Removes and returns the top of the stack.

*@return either the object at the top of the stack or the null if * the stack was empty */

public Object pop();

/** Task: Retrieves the top of the stack.

*@return either the object at the top of the stack or null if * the stack is empty */

(6)

STACK INTERFACE

/** Task: Determines whether the stack is

empty.

*@return true if the stack is empty */

public Boolean isEmpty();

/** Task: Removes all entries from the stack */

public Void clear();

(7)

Example : how to use stack methods

StackInterface myStack = new LStack(); myStack.push(“Jim”);

myStack.push(“Jess”); myStack.push(“Jill”); myStack.push(“Jane”); myStack.push(“Joe”0;

String top = (string) myStack.peek();

System.out.println(top + “ is at the top of the stack.”); top = (String) myStack.pop();

System.out.println(top + “ is removed from the stack.”); Top = (String) mystack.peek();

System.out.println(top+ “ is at the top of the stack.”); Top + (String) myStack.pop();

(8)

Linked implementation of a stack

Note: If you use a chain of linked nodes to

implement a stack, the first node should

reference the stack’s top.

public Class LStack implements StackInterface

{

private Node topNode;

// references first node in chain

public LStack()

{

topNode = null;

(9)

Linked implementation of a stack

public void push(Object newEntry)

{

Node newNode = new Node(newEntry, topNode);

topNode = newNode;

} // end push

public Object pop(){

Object topData = null;

if (topNode != null){

topData = topNode.data // getData();

topNode = topNode.next //getNextNode();

} // end if

(10)

Linked implementation of a stack

public Object peek()

{

Object topData = null;

if (topNode != null)

topData = topNode.data //getData();

return topData;

} // end peek

public boolean ismpty(){

return topNode = = null;

} // end isEmpty

public void clear()

{

topNode = null;

(11)

Linked implementation of a stack

privateClass Node {

private Object data; // entry in stack private Node next; // link to next node

private Node(Object dataPortion) //private or public

{

data= dataPortion ; next=null;

}

private Node(Object dataPortion, Node nextNode)

{

data= dataPortion ; next=nextNode; }

} // end Node

(12)

Array implementation of the STACK ADT

• Note: If you use an array to implement a stack, the

array's first element should represent the bottom of the

stack. The last occupied location in the array, then,

represents the stack’s top.

Public Class AStack implements StackInterface{ Private Object [] stack; // array of stack entries

Private int topIndex; // index of top entry

Private static final int DEFAULT_MAX_SIZ = 50;

Public AStack(){

Stack = new Object[DEFAULT_MAX_SIZE] ; topIndex = -1;

(13)

Array implementation of the STACK ADT

public AStack(int maxSize){ stack = new Object[maxSize]; topIndex = -1;

} // end constructor

public Void push(Object newEntry){ topIndex++;

if (topIndex >= stack.Length) // if array is full doubleArray() ; // expand array

stack [topIndex] = newEntry; } // end push

public Object peek(){ Object top = null ;

If (!isEmpty())

Top = stack[topIndex] ; Return top ;

(14)

Array implementation of the STACK ADT

public Object pop(){ Object top = null;

If (!isEmpty()){

Top = stack[topIndex]; Stack[topIndex] = null; topIndex--;

} // end if return top; } // end pop

public Boolean isEmpty(){ return topIndex < 0;

(15)

Vector implementation of a STACK

• Note: If you use a vector to implement a stack,

the vector’s first element should represent the

bottom of the stack. Then the last occupied

location in the vector represents the stack’s top.

import ja.util.Vector;

pblic class VStack implements StackInterface{ private Vector stack; // top of stack is last element

public VStack(){

sack = new Vector(); // vector doubles in size if necessary } // end default constructor

public VStack(int maxSize){

(16)

Vector implementation of a STACK

public void push(Object newEntry){

stack.addElement(newEntry);

} // end push

public Object peek()

{

Object top = null;

if (!isEmpty())

top = stack.lastElment();

return top;

(17)

Vector implementation of a STACK

public Object pop(){ Object top = null;

if (!isEmpty()){

top = stack.LastElement();

stack.removeElementAt(stack.size()-1); } // end if

return top; } // end pop

public Boolean isEmpty(){

returnStack.isEmpty();} // end isempty

public Void clear(){

(18)

STACK applications: Algebraic expressions

Algorithm checkBalance(expression)

// Returns true if the parentheses, brackets, and braces in an expression are paired correctly. isBslanced = true

while ( (isBalanced = = true) and not end of expression){ nextCharacter = next character in expression

switch (nextCharacter){ case’(‘: case ‘[‘: case ‘{‘:

push nextCharacter onto stack break

case ‘)’: case ‘}’: case’]’: If (stack is empty)

isBalanced = false else{

opendelimiter = top of stack pop stack

isBalanced = true or false according to whether openDelimiter and nextCharacter are a pair of delimiters}

(19)

STACK applications: Algebraic expressions

• public Class balanceChecker{

• /** Task: Determines whether the parentheses, brackets, and braces • in a string occur in left/right pairs.

• *@param expression a string to be checked

• *@return true if the delimiters are paired correctly */

public static Boolean checkBalance(String expression){

stackInterface openDelimitrstack = new LinkedStack(); int charactercount = expression.length();

boolean isBalanced = true; int index = 0;

char nextCharacter = ‘ ‘ ;

For (; isBalanced && (index < charactercount); index++){ Nextcharactr = expression.charAt(index);

Switch(nextCharacter) {

case ‘(‘: case ‘[‘: case ‘{‘:

(20)

STACK applications: Algebraic expressions

case ‘)’: case ‘]’: case ‘}’:

if (openDelimiterStack.isEmpty()) isBalanced = false;

else{

Character open = (Character) openDelimiterStack.pop(); Char openDelimiter = open.charValue();

isBalanced = isPaired(openDelimiter, nextCharacter); } // end if

break;

default: break; } // end switch } // end for

if (!opendelimiterStack.isEmpty() isBalanced = false;

return isBalanced;

(21)

STACK applications: Algebraic expressions

• /** Task: Determines whether two delimiters are pair of Parentheses, brackets, or braces.

• *@param open as a character • *@param close as a character

• *@return true if open/close form a pair of parentheses, brackets, • * or braces */

private Static Boolean isPaired(char open, char close)

{

return (open = = ‘(’ && close = = ‘)’) | | (open = = ‘[‘ && close = = ‘]’) || (open = = ‘{‘ && close = = ‘}’); } // end isPaired

} // end BalanceChecker

• The following statements provide an example of how you might use this class:

String expressions = “a {b [c (d + e) /2 – f] + 1”;

Boolean isBalanced = BalanceChecker.checkBalance(expression); If (isBalanced)

System.out.printIn(expression + “ is balanced”);

(22)

STACK applications: infix and postfix algibric expressions

infix and postfix algibric expressions

• - In an infix expression, each binary operator

appears between its operands, as in a + b.

• - In a prefix expression, each binary operator

appears before its operands, as in +ab.

• - In postfix expression, each binary operator

appears after its operands, as in ab+.

• Infix Postfix

• a + b ab +

(23)

Algorithm of converting infix expression to postfix

expression

1. If an operator is ' ^'. You push it onto the stack

regardless of what is at the top of the stack.

2. Operand : Append each operand to the end of the

output expression.

3. Operator +, -, *, or/: Pop operators from the stack,

appending them to the output expression, until the

stack is empty or its top has a lower precedence than

the new operator. Then Push the new operator onto the

stack.

4. Open parentheses: Push ( onto the stack.)

(24)

Algorithm of converting infix expression to postfix

expression

• 1.when the expression is defined with right precedence

class InfixToPostfix {

public static void main(String[] args) { char[ ] a = args[0].toCharArray(); int N = a.length;

charStack s = new charStack(N); for (int i = 0; i < N; i++)

{ if (a[i] == ')')

Out.print(s.pop() + " ");

else if ((a[i] == '+') || (a[i] == '*') || (a[i] == '/') || (a[i] == '-') || (a[i] == '^'))

s.push(a[i]);

(25)

Algorithm of converting infix expression to postfix

expression

• 2. When the expression not fully defined with

precedence

– operatorStack = a new empty stack – postfix = a new empty string

– while (infex has characters left to parse){

• nextCharacter = next nonblank character of infix • switch (nextCharacter){

– case variable: Append nextCharacter to postfix ; Break – Case ‘^’: operatorStack.push(nextCharacter); break – case ‘+’: case ‘-‘: case ‘*’: case ‘/’:

» while (!operatorStack.isEmpty() and precedence of nextCharacter <= precedence of operatorStack.peek()){

- Append operatorStack.peek() to postfix

- operatorStack.pop()}

(26)

Algorithm of converting infix expression to postfix

expression

– case ‘(‘: operatorStack.push(nextCharacter); break; – case ‘)’: // stack is not empty if infix expressions is valid

• topOperator = operatorStack.pop() • while (topOperator != ‘(‘) {

» Append topOperator to postfix

» topOperator = operatorStack.pop()}

• break;

– default: break; }// end switch }// end while

– while (!operatoStack.isEmpty()){

• topOperator = operatorStack.pop() • Append topOperator to postfix}

(27)

Implementation code for converting infix to

postfix expression

Public Class Postfix{

/** Task: Creates a postfix expression that represents a given infix expression.

*@param infix a string that is a valid infix expression

*@return a string that is the postfix expression equivalent of infix*/

public Static String convertToPostfix(String infix){

StringBuffer postfix = new StringBuffer();

StackInterface operatorStack = new LStack(); Int characterCount = infix.Length();

Character top;

Char topOperator;

For (int index = 0; index < characterCount; index++){ Boolean done = false;

(28)

Implementation code for converting infix to

postfix expression

If(isDigit(nextCharacter))

Postfix = postfix.append(nextcharacter); else{

Switch (nextCharacter){

case ‘^’: operatorStack.push(new Character(nextCharacter)); break;

case ‘+’: case ‘-‘: case ‘*’: case ‘/’:

while (!done && !operatorStack.isEmpty()) {

top = (Character) operatorStack.peek(); topOperator = top.charVal();

if (getPrecedence(nextCharacter)<= getPrecedence(topOperator)) {

postfix = postfix.append(topOperator); operatorStack.pop();

} else

done = true; }// end while

(29)

Implementation code for converting infix to

postfix expression

case ‘(‘:

operatorStack.push(new Character(nextCharacter)); break;

case ‘)’: // stack is not empty if infix expression is valid top = (Character) operatorStack.pop();

topOperator = top.charValue(); while (topOperator != ‘(‘)

{

postfix = postfix.append(topOperator); top = (Character) operatorStack.pop(); topOperator = top.charValue();

} // end while break ;

default: break; } // end switch } // end if

(30)

while (!operatorStack.isempty()) {

top = (Character) operatorStack.pop(); postfix = postfix. Append ( top.charValue()); } // end while

return postfix.toString(); } // end convertToPostfix

/** Task: Determines the precedence of a given operator. *@param operator a character that is (, ), +, -, *, /, or ^

*@return an integer that indicates the precedence of operator:

* 0 if “(“ or “)”, 1 if “+” or” –”, 2 if ”*” or “/”, 3 if “^”, -1 if anything else*/

private static int getPrecedence(char operator){

switch (operator){

case ‘(‘: case ‘)’: return 0; case ‘+’: case ‘-‘: return 1; case ‘*’: case ‘/’: return 2; case ‘^’: return 3; } // end switch

return -1;

} // end getPrecedence

private Static Boolean isDigit(char character){

return Charactr.isDigit(character);} // end isDigit

} // end postfix

(31)

Algorithm of evaluating the Postfix

• // Evaluates a postfix expression. 1. initialize empty stack

valueStack = a new empty stack 2. scan the postfix expression

while (! End of postfix expression ){ do the following a. get next token(character)

nextCharacter = next nonblank character of postfix b. check what the token is:

switch ( nextCharacter ){

i- case variable: push it onto the stack

valueStack.push(valu of the variable nextCharacter) ii- case ‘+’; case ‘-‘: case ‘*’: case ‘/’: case ‘^’:

pop the two operands from stack; do operation; then push the result operandTwo = valueStack.pop( )

operandOne = valueStack.pop( )

result = operandOne operation operandTwo valueStack.push ( result )

iii- default: break } } 3. return the result

(32)

Implementation of evaluating postfix

expression

• /** Task: return the result of evaluating a given postfix expression expression.

• *@param postfix a string that is a valid postfix expression

• *@return an integer value that is the result of evaluating the postfix expression */

public static int evaluatePostfix(String postExp){ StackInterface valueStack = new LStack();

int characterCount = postExp.length(); String operandOne,operandTwo;

int oper1,oper2;

for (int index = 0; index < characterCount; index++){ char nextCharacter = postExp.charAt(index);

if(isDigit(nextCharacter))

(33)

Implementation of evaluating postfix

expression

else{

switch (nextCharacter){

case '+': case '-': case '*': case '/':case '^': operandTwo=(String)valueStack.pop();

operandOne=(String)valueStack.pop(); oper1 =Integer.parseInt(operandOne); oper2=Integer.parseInt(operandTwo);

int result= operation(oper1,oper2,nextCharacter); valueStack.push(new Integer(result).toString()); break;

} } }

int finalResult=Integer.parseInt( (String)valueStack.pop ()); return finalResult;

(34)

Implementation of evaluating postfix

expression

private static Boolean isDigit(char character){ return Character.isDigit(character);

} // end isDigit

private static int operation(int o1,int o2, char opchar){ int z=0;

switch(opchar){

case '+' : z= o1+o2;break; case '-' : z= o1-o2;break; case '*' : z= o1*o2;break; case '/' : z= o1/o2;break;

case '^' : z= (int)Math.pow(o1,o2);break; }

return z; }

(35)

Implementation of evaluating the Postfix when the

postfix given through the command line

class Postfix {

public static void main(String[] args) { char[] a = args[0].toCharArray(); int N = a.length;

intStack s = new intStack(N); for (int i = 0; i < N; i++)

{ if (a[i] == '+')

s.push(s.pop() + s.pop()); else if (a[i] == '*')

s.push(s.pop() * s.pop()); else if ((a[i] >= '0') && (a[i] <= '9')) s.push(0);

while((a[i] >= '0') && (a[i] <= '9')) s.push(10*s.pop() + (a[i++]-'0')); }

(36)

Stack applications:- reverse a string

public class ClientStack{

public static void main(String org[])

{ String strReversed=JoptionPane.showInputDialog(“enter ur string”); StackInterface stk=new LStack();

int index=0;

char nextCharacter =’’;

for(index=0;index<strReverseed.length();index++) { nextCharacter=strReversed.charAt(index);

stk.push(new Character(nextCharacter)); }

while (!stk.isEmpty())

{ Character ch = (Character)stk.pop(); char c=ch.charValue();

s.o.p(c); }

(37)

Stack applications:- check palindrome strings

Public class clientstack{

Public static void main(String org[])

{ String strpl=JoptionPane.showInputDialog(“enter ur string”); StackInterface stk=new LStack();

Int index=0;

Char nextCharacter =’’;

For(index=0;index<strpl.length();index++) { nextCharacter=strpl.charAt(index);

stk.push(new Character(nextCharacter)); }

index=0;

while (!stk.isEmpty())

{ Character ch = (Character)stk.pop(); char c=ch.charValue();

if(!(c. equals(strpl.charAt(index))) ) break;

}

if(stk.isEmpty()) s.o.p(“ur string palindrome); else s.o.p(“ur string not palindrom”)

(38)

Binary search using recursion

public Bolean contains(Object desiredItem){

return binarySearch(0, Length-1, (comparable)desirdItem); } // end contains

/** Task: Searches entry[first] through entry[last] for desiredItem, where the array entry is a data field. *@param first an integer index >= 0 and < Length of list *@param last an integer index >= 0 and < Length of list *@param desiredItem the object to be found in the array *@return true if desiredItem is found */

private Boolean binarySearch(int first, int last, comparable desiredItem){ Boolean found:

Int mid = (first + Last)/2; If (first > Last)

Found = false;

Else if (desiredItem.equals(entry[mid])) Found = true;

Else if (desiredItem.compareTo(entry[mid]) < 0) Found = binarySearch(first, mid-1, desiredItem); Else

Found = binarySearch(mid+1, Last, desiredItem); Return found;

(39)

Binary search using stack

private Class Record{ privte int first, Last;

private Record(int firstIndex, int LastIndex){ first = firstIndex;

Last = LastIndex; } // end constructor } // end Record

private Boolean binarySearch(int first, int Last, comparable desiredItem){ StackInterface programStack = new AStack();

Boolean found = false; Boolean done = false;

programStack.push(new Record(first, Last)); while (!done && !programStack.isEmpty()){

Record topRecord = (Record)programStack.pop(); First = topRecord.first;

Last = topRecord.Last; Int mid = (first + Last) / 2;

If (first > Last){ Found = false; Done = true;}

else if (desiredItem.equals(entry[mid])){ Found = true; Done = true;} else{

If (desiredItem.compareTo(entry[mid]) < 0) programStack.push(new Record(first, mid-1)); else

programStack.push(new Record(mid+1, Last)) } // end if } // end while

return found;

References

Related documents