+ All Categories
Home > Documents > CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack...

CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack...

Date post: 26-Mar-2015
Category:
Upload: melanie-cooper
View: 229 times
Download: 1 times
Share this document with a friend
Popular Tags:
33
CS2006 - Data Structures I Chapter 6 Stacks I
Transcript
Page 1: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

CS2006 - Data Structures I

Chapter 6Stacks I

Page 2: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

2

Topics

ADT Stack Stack Operations Using ADT Stack

Line editor Bracket checking Special-Palindromes

Implementation of ADT Stack Using Arrays

Page 3: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

3

Introduction

Stack: Ordered group of homogeneous items Only one item can be accessed at a time (top) Items addition / removal take place only at the

top Inserting an item is known as "pushing"

onto the stack. Removing an item is known as "popping" off the stack.

Has Last-In-First-Out (LIFO) behavior

Page 4: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

4

Stack Of Cups

Add a cup to the stack.

bottom

top

C

A

B

D

E

F

• Remove a cup from new stack.

bottom

top

C

A

B

D

E

Page 5: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

5

Introduction

Real-life examples: Trays Pennies Folded shirts Books . . .

Very useful in computer science Converting numeric strings into equivalent values Evaluating algebraic expressions

Page 6: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

6

LIFO

A stack is a LIFO (Last-in-first-out) list

1234

12345

12345

pushpush

1234

1234 5

poppop

toptop

bottombottomstack depth = 5stack depth = 5

Page 7: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

7

Introduction

Example: Line-editora b c c d d d e e f f g

means backspace will generate the following output:

a b c d e f g

Observations

Page 8: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

8

Introduction Example: Line-editor

Pseudocode: // Read the line, correcting mistakes along the waywhile (not end of line){

Read a new character chif ( ch is not a ‘ ‘ )

Add ch to the ADTelse

Remove the most recently added item from the ADT

} // end while

Page 9: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

9

Introduction Writing the line:

First Draft:

// Write the line while (the ADT is not empty){

Remove most recently added item from the ADT

Write item ......... } // end while

Page 10: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

10

Introduction

Example: Line-editor The following operations are needed

Determine if the line is empty Add a character Remove the most-recently added character Retrieve the most recently added item

These are exactly the operations needed for a stack The ADT Stack can be used to perform the reading

and correction of the line

Page 11: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

11

The Stack Interface In Java We can define our own stack interface like this:

public interface StackInterface {

public boolean isFull(); // returns if the stack is full

public boolean isEmpty(); // return if the stack is empty public Object top() // return the top element

throws StackException; // if the stack is empty

public void push(Object obj); // push obj onto the stack

public void popAll ();

public Object pop() // return and remove the // top element of the stack

throws StackException; // if the stack is empty}

Page 12: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

12

Using ADT Stack

Read & Correct a text of line: Using stack operations

+readAndCorrect( out aStack : Stack)// Reads input line and either enters characters onto stack S// or corrects contents if the character is the ‘ ‘ symbolaStack.createStackRead newCharwhile ( newChar != eoln ){ if ( newChar != ‘ ‘ )

aStack.Push( newChar)else if (! aStack.isEmpty())

aStack.Pop( )read newChar

} // end while

Page 13: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

13

Using ADT Stack

Write Backwards using ADT stack operations:+displayBackward ( in aStack ; Stack)

// Displays input line in reverse order by writing

// the contents of stack aStack

while ( ! aStack.isEmpty ( ) )

{ aStack.pop ( newChar )

write newChar

} // end while

Page 14: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

14

Stack Application

Example: Balanced Braces Assumption

All braces are of the same type Example:

a b c { d e f g { i j k } { l { m n } } o p } q r Balanced

a b c { d e f } } { g h I j { k l } m Unbalanced

Page 15: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

15

Stack Application

Balanced Braces Idea:

keep track for unmatched ‘{‘ by pushing them onto a stack When ‘}’ is encountered , pop one of the unmatched ‘{‘ from

the stack Stop when

The string and stack are both empty Success

Stack is empty, but string still contains closing braces (‘}‘) Failure: more closing braces

String is empty but stack still contains unmatched opening braces (‘{‘’)

Failure: more opening braces

Page 16: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

16

Stack Application Balanced Braces: Pseudocode

aStack.createStack ( )balancedSoFar = truei = 0while ( balancedSoFar and i < length of aString){ ch = character at position i

++ iif ( ch = ‘{‘)

aStack.push( ‘{‘ )else if ( ch = ‘}’ )

aStack.pop( ) // Pop a matching open brace

else balancedSoFar = false// ignore all characters other that braces

} // end while

if ( balancedSoFar && aStack.isEmpty( ) )aString has balanced braces

elseaString doesn’t have balanced braces

Page 17: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

17

Stack Application

Balanced Braces: Examples

{ a { b } c }

{ a { b c }

{ a b } }

Page 18: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

18

Stack Application

How about math expression with 3 types of brackets

() [] {}

Page 19: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

19

Stack Application

Algorithm Scan expression from left to right Each time a left bracket is encountered, push it onto

stack When a right bracket is encountered, compare it with

the top item on the stack If it is a match, pop the stack If not, report illegal bracketing If the stack id prematurely empty, report illegal If there are items left on the stack after the expression has

been scanned, report illegal bracketing

Page 20: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

20

Stack Application

(3+4)*{7+[4/8]}

Page 21: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

21

Stack Application

Special-Palindromes L = { w $ w ' : w is either empty or any string not including $,

and w ' = reverse (w) } Idea:

Traverse the first half and push its elements onto the stack When $ is reached, ignore it and start traversing and

matching each element from the input string with that on the stack

Termination: Success:

Both stack and string are empty Failure:

Character on input doesn't match character on stack top String empty, but stack isn't Stack empty, but string isn't

Page 22: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

22

Stack Application Special-Palindromes: Pseudocode using ADT Stack

aStack.createStack ( )// Push characters preceding $ onto stacki = 0 ch = character at position i in stringwhile ( ch != ‘$’){ aStack.Push ( ch )

++i ch = character at position i in string} // end while++i // Skip the ‘$// match the reverse of winLanguage = true // assume string is in languagewhile ( inLanguage && i < length of aString)try { aStack.pop (StackTop)

ch = character at position i in stringif ( StackTop = ch

++i // Characters matchelse inLanguage = false

} // end trycatch { // pop failed, stack empty (1st half of string shorter than

2nd halfinLanguage = false

} // end catchIf (inLanguage && isEmpty())

aString is in languageElse

aString is not in language

Page 23: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

23

ADT Stack Implementation

implementations Arrays Linked lists ADT List Vector

Page 24: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

24

ADT Stack Implementation

Array Linked List ADT List

10

20

30

Top10

20

30

Top10

20

30

Top

Page 25: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

25

An Array-Based Stack We can use arrays for our stacks by requiring a maximum

size N for our stack (e.g. N = 50) The stack would then consist of an N-element array, s, and

the array index of the top element, t

Array indices start at 0,so we will initialize t to -1 Pseudo-code:

int size(): return t +1

boolean isEmpty(): return t < 0Object top(): if isEmpty() then throw

StackEmptyException else return s [t ]

Page 26: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

26

Stack Interface

public interface StackInterface { public boolean isEmpty(); public boolean isFull(); public void push(Object newItem) throws

StackException; public Object pop() throws StackException; public void popAll(); public Object peek() throws StackException;

} // end StackInterface

Page 27: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

27

Stack Exception

public class StackException extends java.lang.RuntimeException { public StackException(String s) { super(s); } // end constructor} // end StackException

Page 28: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

28

Array Stack Implementation (1)public class ArrayStackBased implements StackInterface { final int MAX_STACK = 50; // maximum size of stack private Object items[ ]; private int top;

public ArrayStackBased() { items = new Object[MAX_STACK]; top = -1; } // end default constructor

public boolean isEmpty() { return top < 0; } // end isEmpty

public boolean isFull() { return top == MAX_STACK-1; } // end isFull

Page 29: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

29

Array Stack Implementation (2)

public void push(Object newItem) throws StackException { if (!isFull()) { items[++top] = newItem; } else { throw new StackException("StackException on " + "push: stack full"); } // end if } // end push

public void popAll() { items = new Object[MAX_STACK]; top = -1; } // end popAll

Page 30: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

30

Array Stack Implementation (3) public Object pop() throws StackException { if (!isEmpty()) { return items[top--]; } else { throw new StackException("StackException on " + "pop: stack empty"); } // end if } // end pop

public Object peek() throws StackException { if (!isEmpty()) { return items[top]; } else { throw new StackException("Stack exception on " + "peek - stack empty"); } // end if } // end peek} // end ArrayStack

Page 31: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

31

Array Stack Test public class ArrayStackTest { public static final int MAX_ITEMS = 15; public static void main(String[ ] args) { ArrayStackBased stack = new ArrayStackBased(); Integer items[ ] = new Integer[MAX_ITEMS]; System.out.println("Pushing:"); for (int i=0; i<MAX_ITEMS; i++) { items[i] = new Integer(i); if (!stack.isFull()) { System.out.print(" "+i); stack.push(items[i]); } // end if } // end for System.out.println("\nPopping:"); while (!stack.isEmpty()) { // cast result of pop to Integer System.out.print(" "+(Integer)(stack.pop())); } // end while System.out.println(); } // end main} // end ArrayStackTest

Page 32: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

32

Array Stack Test Output

Pushing:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

Popping:

14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

Page 33: CS2006 - Data Structures I Chapter 6 Stacks I 2 Topics ADT Stack Stack Operations Using ADT Stack Line editor Bracket checking Special-Palindromes Implementation.

33

Array Stack

Questions: Can we push/pop primitive type value onto the

stack? Can we push/pop different objects onto the stack?

Student

Car

How to access each object


Recommended