Presentation is loading. Please wait.

Presentation is loading. Please wait.

Stacks.

Similar presentations


Presentation on theme: "Stacks."— Presentation transcript:

1 Stacks

2 Data Structure: Stacks
Outline Linked-list Implementation Array Implementation Applications 4/26/2019 Data Structure: Stacks

3 Data Structure: Stacks
Stack ADT 2 List A1, A2, …, AN If N=0, it is an empty stack. Methods Push: add the element on the top of stack Pop: take the element from the top of stack Top: read the element on the top of stack pop push topOfStack 7 1 8 3 4 4/26/2019 Data Structure: Stacks

4 Linked-list Implementation
public class StackLi { public StackLi() { topOfStack=null; } public boolean isFull() { return false; } public void makeEmpty() { topOfStack=null; } ... private ListNode topOfStack; } A5 topOfStack A4 A3 A2 A1 4/26/2019 Data Structure: Stacks

5 Data Structure: Stacks
Method push, pop, top public void push(object x) { topOfStack = new ListNode(x, topOfStack); } public void pop() throws Underflow { if (isEmpty()) throw new Underflow(); topOfStack = topOfStack.next; public Object top() { if (isEmpty()) return null; return topOfStack.element; 4/26/2019 Data Structure: Stacks

6 Data Structure: Stacks
Method topAndPop public Object topAndPop() { if (isEmpty()) return null; Object topItem = topOfStack.element; topOfStack = topOfStack.next; return topItem; } 4/26/2019 Data Structure: Stacks

7 Data Structure: Stacks
Array Implementation public class StackAr { public StackAr() { this(DEFAULT_SIZE); } public StackAr(int size) { theArray = new Object [size]; topOfStack=-1;} public boolean isEmpty() { return topOfStack==-1; } public boolean isFull() { return topOfStack== theArray.length-1;} ... private Object [] theArray; private int topOfStack; static final int DEFAULT_SIZE=10; } 6 5 A6 4 A5 3 A4 2 A3 1 A2 A1 topOfStack=5 4/26/2019 Data Structure: Stacks

8 Data Structure: Stacks
Method push, pop, top public void push(object x) throws Overflow { if (isFull())throw new Overflow(); theArray[++topOfStack] = x; } public void pop() throws Underflow { if (isEmpty()) throw new Underflow(); theArray[topOfStack--] = null; public Object top() { if (isEmpty()) return null; return theArray[topOfStack]; 4/26/2019 Data Structure: Stacks

9 Data Structure: Stacks
Method topAndPop public Object topAndPop() { if (isEmpty()) return null; Object topItem = theArray[topOfStack]; theArray[topOfStack--] = null; return topItem; } 4/26/2019 Data Structure: Stacks

10 Application:Balancing Parenthesis
( ( ( ) ( ) ( ( ) ( ) ) ) ( ) ) StackLi symStk=new StackLi; Object sym=nextsym(); while (sym!=null) { if (sym.isOpenPar()) symStk.push(sym); if (sym.isClsPar()) if (!symStk.isEmpty()) symStk.pop(); else return false; sym=nextsym(); } return symStk.isEmpty(); ( ( ( ( 4/26/2019 Data Structure: Stacks


Download ppt "Stacks."

Similar presentations


Ads by Google