Sei sulla pagina 1di 27

Stacks

What is stack?

A stack is an abstract data type (ADT),


commonly used in most programming
languages. It is named stack as it behaves
like a real-world stack, for example deck
of cards or pile of plates etc.

What is stack?
Stack ADT allows all data operations at one
end only. At any given time, We can only
access the top element of a stack.
This feature makes it LIFO data structure.
LIFO stands for Last-in-first-out. Here, the
element which is placed (inserted or added)
last, is accessed first. In stack terminology,
insertion operation is
calledPUSHoperation and removal
operation is called POP operation.

Basic Operations

Stack operations may involve initializing the stack, using it


and then de-initializing it. Apart from these basic stuffs, a
stack is used for the following two primary operations
push() pushing (storing) an element on the stack.
pop() removing (accessing) an element from the stack.
When data is PUSHed onto stack.
To use a stack efficiently we need to check status of stack
as well. For the same purpose, the following functionality
is added to stacks
peek() get the top data element of the stack, without
removing it.
isFull() check if stack is full.
isEmpty() check if stack is empty.

Array Representation of
Stacks
XXX
1

YYY

ZZZ

TOP

8
MAXSTK

Push Operation
PUSH(STACK, TOP, MAXSTK, ITEM)
This procedure pushes an ITEM onto a stack
1. If TOP=MAXSTK then print OVERFLOW and
Return
2. Set TOP:=TOP+1
3. Set STACK[TOP]:=ITEM
4. Return

Pop Operation
POP(STACK, TOP, ITEM)
This procedure deletes the top element of
STACK and assigns it to the variable ITEM
1. If TOP=0 then print UNDERFLOW and
Return
2. Set ITEM:=STACK[TOP]
3. Set TOP:=TOP-1
4. Return

Linked Representation of Stacks


The linked stack is a stack that is implemented using a
singly linked list. The INFO fields of the nodes hold
the elements of the stack and the LINK fields hold
pointers to the neighboring element in the stack. The
START pointer of the linked list behaves as the TOP
pointer variable of the stack and the null pointer of the
last node in the list signals the bottom of stack.

Linked Representation of Stacks


TOP

XXX
INFO

YYY
LINK

Top of stack

ZZZ
Bottom of
stack

Push Operation
PUSH_LINKSTACK(INFO,LINK,TOP,AVAIL,ITEM)
1. If AVAIL=NULL, then Write OVERFLOW and Exit.
2.Set NEW :=AVAIL and AVAIL:=LINK[AVAIL]
3.Set INFO[NEW]:=ITEM
4.Set LINK[NEW]:=TOP
5.Set TOP=NEW
6.Exit

Pop Operation
POP_LINKSTACK(INFO,LINK,TOP,AVAIL,ITEM)
1.IF TOP=NULL the Write: UNDERFLOW and Exit
2.Set ITEM:=INFO[TOP]
3.Set TEMP:=TOP and TOP=LINK[TOP]
4.Set LINK[TEMP]=AVAIL and AVAIL=TEMP
5.Exit

Infix Notation
To add A, B, we write
A+B
To multiply A, B, we write
A*B
The operators ('+' and '*') go in between the operands
('A' and 'B')
This is "Infix" notation.

Prefix Notation
Instead of saying "A plus B", we could say "add A,B "
and write
+ AB
"Multiply A,B" would be written
*AB
This is Prefix notation.

Postfix Notation
Another alternative is to put the operators after the
operands as in
AB+
and
AB*
This is Postfix notation.

Parentheses
Evaluate 2+3*5.
+ First:
(2+3)*5 = 5*5 = 25
* First:
2+(3*5) = 2+15 = 17
Infix notation requires Parentheses.

What about Prefix Notation?


+2*35=
=+2*35
= + 2 15 = 17
*+235=
=*+235
= * 5 5 = 25
No parentheses needed!

Postfix Notation
235*+=
=235*+
= 2 15 + = 17
23+5*=
=23+5*
= 5 5 * = 25
No parentheses needed here either!

Example: postfix expressions


Postfix

notation is another way of writing arithmetic


expressions.

In

postfix notation, the operator is written after the two


operands.

infix: 2+5 postfix: 2 5 +


Expressions are evaluated from left to right.
Precedence

rules and parentheses are never needed!!

Example: postfix expressions


(cont.)

Infix to postfix using stack


Algorithm
a)Create a stack
b)for each character t in input stream{
if(t is an operand)
output t
else if(t is a right parenthesis){
Pop and output tokens until a left parenthesis is popped(but not
output)
}
else //t is an operator or left parenthesis{
pop and output tokens until one of lower priority than t is encountered or a left
parenthesis is encountered or stack is empty
Push t
}
}
c)pop and output tokens until the stack is empty

Postfix evaluation
Algorithm
1.Scan the Postfix string from left to right
2.Initialize an empty stack.
3.Repeat steps 4 and 5 till all the characters are scanned.
4. If the scanned character is an operand, push it onto the stack.
5.If the scanned character is an operator, and if the operator is unary
operator then pop an element from the stack. If the operator is binary
operator then pop two elements from the stack. After popping the
elements, apply the operator to those popped elements. Let the result of
this operation be retVal onto the stack.
6.After all characters are scanned, we will have only one element in the
stack.
7. Return top of the stack as result

Prefix evaluation
Given infix expression: 4 $ 2 * 3 3 + 8 / 4 / ( 1 + 1 )
Steps:
1.Reverse the expression.
)1+1(/4/8+33*2$4
2.The prefix string is filled from right to left. Initialize a stack.
a)Add left parenthesis ) to stack.
b)Add 1 to prefix string
c)Push + on stack
d)Add 1 to prefix string
e)Operator ( is scanned, + is popped from stack. Add + to prefix
string, ) is popped from stack.
f)Push / on to stack
g)Add 4 to prefix string
h)As hierarchy are same push / onto stack
i)Add 8 to prefix string

Prefix evaluation
j)As hierarchy of + is less than /,/ is popped from stack
and added to prefix string
k)Second / is also popped similarly and added to prefix
string.+ is pushed to stack.
l)3 is added to prefix string.
m)As hierarchy of + is same as -, - is pushed onto stack.
n) 3 is added to prefix string.
o)* is scanned, its hierarchy is greater than so it is
pushed to stack
p)2 is added to prefix string.

Prefix evaluation
q)As hierarchy of $ is greater than *, it is pushed to
stack.
r)4 is added to prefix string
s)$, *,-,+ are added to the prfix string respectively.
Final expression obtained is:
+-*$4233//84+11

Implementing stack using


queue
Stack can be implemented by using two queues
struct Stack{
struct Queue *Q1;
struct Queue *Q2;
}
In the algorithm below we ensure that one queue is
always empty.
Push operation Algorithm: Insert the element in
whichever queue is not empty.
Check whether queue Q1 is empty or not. If Q1 is
empty then Enqueue the element into Q2.
Otherwise Enqueue the element into Q1.

Push(struct Stack *S,int data){


If(IsEmptyQueue(S->Q1))
EnQueue(S->Q2,data)
else
EnQueue(S->Q1,data)
}
Time Complexity: O(1)

Pop Operation Algorithm: Transfer n-1elements to the other queue and delete
last from queue for performing pop operation.
If Queue Q1 is not empty then transfer n-1 elements from Q1 to Q2 and then,
Dequeue the last element of Q1 and return it.
If Queue Q2 is not empty then transfer n-1 elements from Q2 to Q1 and then,
Dequeue the last element of Q2 and return it.

int pop(struct stack *S){


int i,size;
if(IsEmptyQueue(S->Q2)){
size=size(S->Q1);
i=0;
while(i<size-1){
EnQueue(S->Q2,DeQueue(S->Q1));
i++;
}
return Dequeue(S->Q1);
}
else{ size=size(S->Q2);
while(i,size-1){
EnQueue(S->Q1,DeQueue(S->Q2));
i++;
}
return DeQueue(S->Q2);
}
}
Time Complexity : Running time of pop operation is O(n).

Potrebbero piacerti anche