What are Stacks
The first Data Structure that we learn is called a stack .
push
pop
Operations:
• Push: Put a new plate on top ox the stack of plates.
• Pop: Take out a plate from the stack of plates.
Page x3 of 50
What are Stacks
In computer science, we use stacks to store values.
S
x tack of push
27
Integers
x 27 5 5
10 x0 10
1 1 1
23 23 x3
Stack ofx
Integers pop
2
45 45 2 45
63 63 63
4 4 4
Page 14 of 50
What are Stacks
In computer science, we use stacks to store values.
Stack
x of push
's'
x
characters s
'p' 's' 'p' 'p'
'p' 'p' 'p'
'm' 'm' 'm'
‘b' 'b' 'b'
Stack of
characters pop
o
'z'
‘e' 'e' 'x' 'e'
'd' 'x' 'x'
'a' 'a' 'a'
Page 15 of 50
What are Stacks
In computer science, we use stacks to store values.
Stack ofo push
7.8
floats
0.6 7.8 0.6 0.6
4.2 4.3 4.3
1.1 1.1 1.1
0.8 0.8 2.8
Stack of
floats pop
0.1
2.4 2.4 0.1 2.4
0.7 0.4 0.7
0.5 0.5 0.5
Pxge 16 of 50
What are Stacks
In computer science, we use stacks to store values.
s
Stack of p
xush
shapes
Stackkof
shapes pop
Page 17 of 50
Stack Operations
The push operation puts a new value on the top of a stack
push
Page 18 of 50
Stack Operations
The pop operation takes x value from the top ox a stack.
pop
This value is re-
turned by pop .
Usually ‘ pop ’ is seen as a function, which returns the valu
originally stored at the top of the stack.
Page 19 of 50
Stack Operations
A stack is a Last-In-First-Out (LIFO) structure.
p
xush pop
5
4 5 4 4 4 5 4
3 3 3 3 3
2 2 2 2 2
1 1 1 1 1
Page 20 of 50
Stack Terminologies
top
xstack
depth = 4
bottom
a stack
element an empty
stack
Page 21 of 50
Defining a Stack ADT
We see that STACK is an Abstract Data Type.
isEmpty
pop
p
xush
…
Page 22 xf 50
Sample Application: Matching Parentheses
- Stack is a very useful data structure specially in the construction of
compiler for programming languages.
- Note that a compiler checks whether the symbols that you use in your
programs like {} match.
- We will now try to create a simple function that accepts an expression
containing parentheses and will return true if the parentheses in the
expression match, otherwise will return false;
- the function will use a stack as follows:
* the string is processed one character at a time.
* If a '(' is encountered, a Character object is created representing
'(' and is pushed on the stack.
* If a ')' brace is encountered, the stack is popped. If the stack is
empty, the operation is terminated meaning that there is no
corresponding '('.
* At the end of the processing, the stack should also be empty.
*
Defining the Type stackADT
void push(int element);
int pop();
int stackDepth();
boolean isEmpty();
xage 23 of 50
Notes
This defines an API that describes the stack ADT.
void push(int element);
push
Page 24 of 50
public int pop();
pop
Page 25 of 5x
int stackDepth();
This returns the depth of a stack.
boolean isEmpty();
This tells whether a stack is empty.
void clear()
makes the stack an empty stack
int top()
returns the top item of the stack
Page 26 of 50