24
Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

Embed Size (px)

Citation preview

Page 1: Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

Data Structures

Lecture 8: Stacks

Azhar MaqsoodNUST Institute of Information Technology (NIIT)

Page 2: Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

The Stack: Definition

• A stack is an ordered collection of items into which new items may be inserted and from which items may be deleted at one end called the TOP of the stack

Page 3: Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

Stack

• The definition of stack provides for the insertion and deletion of items, so that a stack is a dynamic, constantly changing object.

• How does a stack change?

Page 4: Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

Stack

• New items may be put on top of the stack– In which case the top of the stack moves upward

to correspond to the new highest element

• Items which are at the top of the stack may be removed – In which case the top of the stack moves

downward to correspond to the new highest element.

• Which way is up???– We must decide which end of the stack is

designated as its top.

Page 5: Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

What is a Stack

• A common data structure in computing.

• Data items are "popped" and "pushed" (retrieved and stored) from the top of the stack.

• Stacks normally have a maximum size. It is an error to push items onto a full stack, or pop items off an empty stack.

• LIFO: Last In First Out

Page 6: Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

Application

• Parsing of algebraic expression…

• Banking Transaction View– You view the last transaction first.

• Inventory Systems like Issuing students the Multi-meters… you will be issued the most recently returned item likely

Page 7: Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

Insertion and Deletion in Stack

• C is the current top element of the stack. If any new items are added to the stack, they are placed on top of C

• If any new items are deleted C is deleted first

CBA

Page 8: Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

Insertion and Deletion in Stack

push D push E pop pop

CBA

DCBA

EDCBA

DCBA

CBA

BA

Page 9: Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

Abstraction of a Stack

• Now, let's think about a stack in an abstract way. I.e., it doesn't hold any particular kind of thing (like books) and we aren't restricting ourselves to any particular programming language or any particular implementation of a stack.

• Stacks hold objects, usually all of the same type. Most stacks support just the simple set of operations we introduced above; and thus, the main property of a stack is that objects go on and come off of the top of the stack.

Page 10: Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

Operation on Stack

• A Stack should have the following methods:

push(item) //Push an item onto the stack

pop( ) //Pop an item off the stack

isEmpty() //Return true if stack is empty.

top( ) //Return value of top item

• Because we think of stacks in terms of the physical analogy, we usually draw them vertically (so the top is really on top).

• There are several ways to implement a Stack in C.

Page 11: Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

Implementing a stack with an array

• Let's think about how to implement this stack in the C programming language.

• An ordered collection of items in C is array• First, if we want to store letters, we can use type char. Next,

since a stack usually holds a bunch of items with the same type (e.g., char), we can use an array to hold the contents of the stack.

• Now, consider how we'll use this array of characters, call it contents, to hold the contents of the stack. At some point we'll have to decide how big this array is; keep in mind that a normal array has a fixed size.

• Let's choose the array to be of size 4 for now. So, an array getting A, then B, will look like:

A B

[0] [1] [2] [3]

Page 12: Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

Array… Stacks cont

• How do we know that which element to pop when user asks a pop operation.. As not all the spaces of array are filled.

• We need another variable (usually Int) to keep track of last pushed index.

• So for each push we add one to top and for each pop we deduct one from top

A B

[0] [1] [2] [3] 1

TOP

Page 13: Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

Array Stack Pictorial ViewSay Array name is CharStacK

A B

[0] [1] [2] [3]

A B C

[0] [1] [2] [3]

A B C D

[0] [1] [2] [3]

A B C

[0] [1] [2] [3]

1

2

3

2

• Push(CharStack,’C’)

• Push(charStack, ‘D’)

• Pop(charStack)

Page 14: Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

• Push Concerns– What if when the stack is full?

• Pop Concerns– What if the stack is empty

• Solution– Before any push check if the stack is already

filled or not. If it is filled then generate error message e.g Stack Overflow

– Before pop check if stack is not already empty

Page 15: Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

A sample Program (Push Pop using Array)

#include<stdio.h>#include<conio.h>#include<stdlib.h>#include <iostream.h>#define length 10int top=-1;int stack[length];void main(){ int ch; do{ cout << endl << "1.push"; cout << endl << "2.pop"; cout << endl << "3.exit"; cout << endl << "enter choice"; cin >> ch;

switch(ch)switch(ch){{case 1:case 1:

push();push();listStack();listStack();break;break;

case 2:case 2:cout << "data poped= " << cout << "data poped= " <<

pop();pop();listStack();listStack();break;break;

case 3:exit(0);case 3:exit(0);}}

} while(1);} while(1);

getch();getch();}}

Page 16: Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

void push(){

int data;if(top+1==length){ cout << "stack overflow\n Cannot enter new data";

return;}top++;cout << "enter the data ";cin >> data;stack[top]=data;

}

int pop()int pop(){{

int tempVar;int tempVar;if(top==-1)//we can also make isEmpty()if(top==-1)//we can also make isEmpty(){{ cout << "stack is underflow (Empty)";cout << "stack is underflow (Empty)"; return(-1);return(-1);}}tempVar=stack[top];tempVar=stack[top];top--;top--;return(tempVar);return(tempVar);

}}

void listStack()void listStack(){{

cout << endl << "The stack is" << endl ;cout << endl << "The stack is" << endl ;for(int i=top;i>=0;i--)for(int i=top;i>=0;i--) cout << stack[i] << endl;cout << stack[i] << endl;

}}

A sample Program (Push Pop using Array)

Page 17: Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

Stack in Problem Solving

• Consider a mathematical expression that includes several sets of nested parenthesis, e.g

( x + (y – (a +b)) )• We want to ensure that parenthesis are nested

correctly and the expression is valid

• Validation1. There is an equal number of right and left

parentheses2. Every right parenthesis is preceded by a

matching left parenthesis

Page 18: Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

Expressions

• (A+B) * C Valid

• A + B) Invalid

• (A+B] Invalid

Page 19: Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

Rules

• Each left parentheses is the opening scope• Each right parenthesis is a closing scope• The number of left parentheses encountered

whose matching right parentheses have not been encountered is nesting depth at that point

• Parentheses count = 0 at the end means that no scopes have been left open and left and right parentheses exactly match

• The parentheses count at any time should never become negative. IF negative then its error.

Page 20: Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

Expressions

• ( ( A + B )

• 1 2 2 2 2 1

• ( A * B )

• 1 1 1 1 0

• A*B(

• 0 0 0 1

ErrorError

RightRight

ErrorError

Page 21: Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

Parsing Parenthesis

• Let us change the problem slightly• Three different kinds of scope delimiters

exist e.g { x + (y – [a +b]) }

• The scope ender must be of same type as scope opener

• It is necessary to keep track of not only the count of scope but also the types

• A stack may be used to keep track of the types of scopes encountered

Page 22: Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

Stacks in validation expression

• Whenever a scope opener is encountered it is pushed into the stack

• Whenever a scope ender is encountered the stack is examined

• If the stack is empty the scope ender does not have a matching opener and string is invalid

• If stack is not empty we pop an item and check if it corresponds to scope ender

• If match occurs we continue, at the end of the string the stack must be empty

Page 23: Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

Pusedo-codeValid = trueS = the empty stack // array of chars say char s[100]While (we have not read the entire string) {

read the next symbol (symb) of the string;if (symb == ‘(‘ || symb == ‘[‘ || symb == ‘{‘)

push (s, symb);if (symb == ‘)‘ || symb == ‘]‘ || symb == ‘}‘) if (empty(s)) valid = false; else {

I = pop (s);if ( I is not the matching opener of symb)

valid = false; }// end of else

} //end whileIf (valid)

cout << “Valid String” << endl;Else

cout << “not a valid string”

Page 24: Data Structures Lecture 8: Stacks Azhar Maqsood NUST Institute of Information Technology (NIIT)

{ x + (y – [a +b]) }

{

(

{

[

(

{

(

{ {

1 2 3 4 5 6 7