Sie sind auf Seite 1von 52

STACKS

• Stack- A stack is a linear data structure in which items may be added


or removed only at one end .
• Accordingly, stacks are also called last-in-first-out or LIFO lists.
• The end at which element is added or removed is called the top of the
stack.

• Two basic operations associated with stacks are :


• Push- Term used to denote insertion of an element onto a stack.

• Pop- Term used to describe deletion of an element from a stack.

The order in which elements are pushed onto a stack is reverse of the

order in which elements are popped from a stack


Representation of stacks
• Stacks may be represented in memory in various ways usually by
means of one-way list or a linear array
In array representation of stack, stack is maintained by an array
named STACK , a variable TOP which contains the location/index of
top element of stack and a variable MAXSTK giving the maximum
number of elements that can be held by the stack. The condition
TOP=0 or TOP=NULL indicates that stack is empty.
The operation of addition of an item on stack and operation of
removing an item from a stack may be implemented respectively by
sub algorithms, called PUSH and POP. Before executing operation
PUSH on to a stack, one must first test whether there is room in the
stack for the new item. If not, then we have the condition known as
overflow. Analogously, in executing the POP operation, one must
first test where there is an element in stack to be deleted. If not, then
we have condition known as underflow.
ARRAY
IMPLEMENTATION
OF STACK
• Algorithm: PUSH (STACK,TOP,MAXSTK,ITEM)
This algorithm pushes an item onto the stack array. TOP
stores the index of top element of the stack and MAXSTK
stores the maximum size of the stack.
• Step 1: [Stack already filled]
If TOP==MAXSTK-1, then:
Write: ‘OVERFLOW’
Return
• Step 2: Set TOP:=TOP+1
• Step 3: Set STACK[TOP]:=ITEM
• Step 4: Return
Algorithm: POP(STACK,TOP,ITEM)
This procedure deletes the top element of
STACK array and assign it to variable ITEM
• Step 1: If TOP== -1,then:
Write: ‘UNDERFLOW’
Return
• Step 2: Set ITEM:=STACK[TOP]
• Step 3: Set TOP:=TOP-1
• Step 4: Return
• A stack represented using a linked list is also known as
linked stack.

• The array based representation of stack suffers from following


limitations:
• Size of stack must be known in advance
• Representing stack as an array prohibits the growth of stack beyond
finite number of elements.
In a linked list implementation of stack, each memory cell will
contain the data part of the current element of stack and pointer that
stores the address of its bottom element and the memory cell
containing the bottom most element will have a NULL pointer
Push operation on linked list representation of stack
• Algorithm: PUSH(INFO, LINK, TOP, ITEM, AVAIL)
This algorithm pushes an element to the top of the stack
Step 1: If AVAIL==NULL, then
Write: ‘OVERFLOW’
Return
Step 2: Set NEW=AVAIL and AVAIL = AVAIL->LINK
Step 3: Set NEW->INFO =ITEM
Step 4: Set NEW->LINK=TOP
Set TOP=NEW
Step 5: EXIT
POP operation on linked list representation of stack
• Algorithm: POP(INFO, LINK, TOP, AVAIL, ITEM)
• This algorithm deletes an element from the top of the
stack
• Step 1: If TOP==NULL , then:
Write: ‘UNDERFLOLW’ AND Exit
• Step 2: Set ITEM = TOP->INFO
• Step 3: Set TEMP = TOP AND TOP= TOP->LINK
• Step 4: TEMP->LINK = AVAIL AND AVAIL = TEMP
• Step 5: EXIT
Application of stack
• Evaluation of arithmetic expression.
• For most common arithmetic operations, operator symbol is placed
between its operands. This is called infix notation of an expression.
To use stack to evaluate an arithmetic expression, we have to convert
the expression into its prefix or postfix notation.
• Polish notation , refers to the notation in which operator symbol is
placed before its two operands. This is also called prefix notation of
an arithmetic expression. The fundamental property of polish notation
is that the order in which operations are to be performed is completely
determined by positions of operators and operands in expression.
Accordingly, one never needs parentheses when writing expression in
polish notation.
• Reverse Polish notation refers to notation in which operator is placed
after its two operands. This notation is frequently called postfix
notation. Examples of three notations are:
• INFIX NOTATION: A+B
• PREFIX OR POLISH NOTATION: +AB
• POSTFIX OR REVERSE POLISH NOATATION: AB+

• Convert the following infix expressions to prefix and postfix forms


• A+(B*C)
• (A+B)/(C+D)
• Prefix: +A*BC Postfix: A BC*+
• Prefix: / +AB+CD Postfix: AB+CD+/
• Example:
• Infix: Postfix/ Prefix
• A + B –C

• (A + B) * (C - D)

• A ^ B * C - D + E / F /(G + H)

• ((A + B) * C – (D - E)) ^ (F + G)

• A - B/(C * D ^ E)

• Example:
• Infix: Postfix/ Prefix
• A+B-C AB + C -
• - + ABC

• (A + B) * (C - D) AB + CD - *
• * + AB - CD

• A ^ B * C - D + E / F /(G + H) AB ^ C * D - EF / GH + / +
• + - * ^ ABCD / / EF + GH

• ((A + B) * C – (D - E)) ^ (F + G) AB + C * DE - - FG + ^
• ^ - * + ABC – DE + FG

• A - B/(C * D ^ E) ABCDE ^ * / -
• - A / B * C ^ DE
The computer usually evaluates an arithmetic expression written in infix
notation in two steps.
• Converts expression to postfix notation
• Evaluates the postfix notation.

• Evaluation of postfix expression


• Suppose P is an arithmetic expression written in postfix notation. The
following algorithm which uses a STACK to hold operands and
evaluates P
• Algorithm: This algorithm finds the VALUE of an arithmetic
expression P written in Postfix notation.
Step 1: Add a right parentheses “ )” at the end of P
Step 2: Scan P from left to right and repeat step 3 and 4 for each element
of P until “)” is encountered
Step 3: If an operand is encountered, put the operand on the stack
Step 4: If an operator is encountered , then:
(a) Remove the two top elements of stack, where A is top element
and B is next-top-element.
(b) Evaluate B A
(c ) Place the result of (b) back on stack
[End of if structure]
[End of step 2 loop]
Step 5: Set VALUE equal to the top element of stack
Step 6: Exit
Transforming Infix Expression into Postfix Expression
• The algorithm uses a stack to temporarily hold operators and left
parentheses. The postfix expression P will be constructed from left to
right using operands from Q and operators which are removed from
STACK. The algorithm begins by pushing a left parentheses onto
stack and adding a right parentheses at the end of Q
• Algorithm: POSTFIX (Q, P)
Suppose Q is an arithmetic expression written in infix
notation. This algorithm finds the equivalent postfix
expression P
Step 1: Push “(“ on to the STACK and add “)” to the end of Q
Step 2: Scan Q from left to right and repeat step 3 to 6 for each element
of Q until the STACK is empty
Step 3: If an operand is encountered, add it to P
Step 4: If left parentheses is encountered, add it to STACK
Step 5: If an operator is encountered, then:
(a) Repeatedly pop from STACK and add to P each operator
which has same precedence or higher precedence than
(b) Add to STACK
Step 6: If a right parentheses is encountered , then:
(a) Repeatedly pop from STACK and add to P each operator until
a left parentheses is encountered
(b) Remove the left parentheses
[End of Step 2 Loop]
Step 7: Exit
• Example: Convert Q=A+(B*C) / D to its corresponding postfix form
• Solution: put “)” at the end of Q and put “(“ on stack
• Starting from left: Operand A , put it on P
• Operator + move to stack as no operator there
• ( move on stack
• Operand B, put it on P
• Operator * , move to stack as no operator
• Operand C , move to P
• ) , pop from stack and put on P until “ (“ is encountered.
• Pop “(“ also
• operator /, as precedence of / is higher than + on stack, no pop
• possible. Push / on stack
• Operand D , put it on P
• Right parentheses ), Pop all the elements and add the P until ( is
encountered. Also remove ( from stack

( /
+ + +
• P= A B C* D / +
( ( (
• Example: Consider the following infix expression Q:
• Q : A + ( B * C – ( D / E ^ F) * G) * H
• Convert Q into it’s postfix expression p using stack.

• Example: Consider the following infix expression :


• A + B / C + D * (E – F) ^ G
• Convert Q into it’s postfix expression using stack.
• Example: Consider the following infix expression Q:
• Q : A + ( B * C – ( D / E ^ F) * G) * H
• Convert Q into it’s postfix expression p using stack.
• Ans: P : A B C * D E F ^ / G * - H * +

• Example: Consider the following infix expression :


• A + B / C + D * (E – F) ^ G
• Convert Q into it’s postfix expression using stack.
• Ans: A B C / + D E F - G ^ * +
Practical applications of stack

• Stacks are used for implementing function calls in a program


• Used for implementing recursion.
• Used for conversion of infix expression to its postfix or prefix form
• Used for evaluation of postfix expression.
• Used in sorting of arrays (quicksort and mergesort technique)
Infix to Postfix Example

A + B * C - D / E

Solve by Yourself:

Infix Stack
Postfix Expression
Postfix Evaulation

Operand: push
Operator: pop 2 operands, do the math, pop result
back onto stack

1 2 3 + *

Postfix Stack[top ]
a) 1 2 3 + *
b) 2 3 + * 1
c) 3 + * 1 2
d) + * 1 2 3
e) * 1 5 // 5 from 2 + 3
f) 5 // 5 from 1 * 5
• Ex:
• Evaluate the following postfix expression
1- p= 5, 6, 2, +, *, 12, 4, /, -

2- p=6, 2, 3, +, -, 3, 8, 2, /, +, *, 2, ^, 3, +

3- Convert infix to postfix and evaluate for a=3, b=4, c=5


Infix: (A+B) *C
• Ex:
• Evaluate the following postfix expression
1- p= 5, 6, 2, +, *, 12, 4, /, -
Ans: 37

2- p=6, 2, 3, +, -, 3, 8, 2, /, +, *, 2, ^, 3, +
Ans: 52

3- Convert infix to postfix and evaluate for a=3, b=4, c=5


Infix: (A+B) *C
Ans: A B +C * and 35
Recursive Solution
Recursive Solution
Recursive Solution
Recursive Solution
Tower of Hanoi
Tower of Hanoi
Tower of Hanoi
Tower of Hanoi
Tower of Hanoi
Tower of Hanoi
Tower of Hanoi
Tower of Hanoi
Recursive Algorithm
TOWER(N, BEG, AUX, END)
1- (If N==1)
1- Write BEG ->END
2- Return
[End of If structure]
2- Call TOWER(N-1, BEG, END, AUX)

3- Write: BEG->END

4- Call TOWER(N-1, AUX, BEG, END)

5- Return
• Let Gn(i) be a function from [0,…,2n-1]

• Total no of moves = 2n -1
Application of Stack: Quick Sort
 It is an algorithm of divide and conquer.

Example
We are given array of n integers to sort:

40 20 10 80 60 50 7 30 70
Pick Pivot Element
There are a number of ways to pick the pivot element. In this
example, we will use the first element in the array:

40 20 10 80 60 50 7 30 70
Quick sort algorithm

QUICKSORT(A,LOW, HIGH)
1:- if(LOW< HIGH)
Pivot = PARTITION(A, LOW,HIGH)
QUICKSORT(A, LOW, Pivot-1)
QUICKSORT(A, Pivot+1, HIGH)
[End of If]
2:-END
Quick sort algorithm
PARTITION(A, BEG, END, LOC)
1. 1- Set LEFT = BEG, RIGHT=END, LOC=BEG
2. 2- [Scan from right to left]
(a) Repeat while A[LOC] <=A[RIGHT] and LOC != RIGHT
RIGHT = RIGHT-1
[End of Loop]
(b) If LOC == RIGHT then return
(c) If A[LOC] > A[RIGHT] then
(i) Interchange A[LOC] and A[RIGHT]
(ii) Set LOC = RIGHT
[End of if structure]
3. 3- [Scan from left to right]
(a) Repeat while A[LEFT] <=A[LOC] and LEFT != LOC
LEFT = LEFT+1
[End of Loop]
(b) If LOC == LEFT then return
(c) If A[LEFT] > A[LOC] then
(i) Interchange A[LEFT] and A[LOC]
(ii) Set LOC = LEFT
(iii) Go to step 2.
[End of if structure]
Complexity of Quick Sort

 Worst case
 O(n2)

 Average case
 O(n log n)
Merge Sort

• Divide and Conquer


• Recursive in structure
– Divide the problem into sub-problems that are similar to the
original but smaller in size
– Conquer the sub-problems by solving them recursively. If
they are small enough, just solve them in a straightforward
manner.
– Combine the solutions to create a solution to the original
problem
An Example: Merge Sort

Sorting Problem: Sort a sequence of n elements into


non-decreasing order.

 Divide: Divide the n-element sequence to be


sorted into two subsequences of n/2 elements each
 Conquer: Sort the two subsequences recursively
using merge sort.
 Combine: Merge the two sorted subsequences to
produce the sorted answer.
Merge Sort – Example
Original Sequence Sorted Sequence

18 26 32 6 43 15 9 1 1 6 9 15 18 26 32 43

18 26 32 6 43 15 9 1 6 18 26 32 1 9 15 43
43

18 26 32 6 43 15 9 1 18 26 6 32 15 43 1 9

18 26 32 6 43 15 9 1 18 26 32 6 43 15 9 1

18 26 32 6 43 15 9 1
Merge-Sort (A, p, r)

INPUT: a sequence of n numbers stored in array A


OUTPUT: an ordered sequence of n numbers

MergeSort (A, p, r) // sort A[p..r] by divide & conquer


1 if p < r
2 then q  (p+r)/2
3 MergeSort (A, p, q)
4 MergeSort (A, q+1, r)
5 Merge (A, p, q, r) // merges A[p..q] with A[q+1..r]

Initial Call: MergeSort(A, 1, n)


Procedure Merge
Merge(A, p, q, r)
1 n1  q – p + 1
2 n2  r – q
3 for i  0 to n1 -1
4 do L[i]  A[p + i ] Input: Array containing sorted subarrays
A[p..q] and A[q+1..r].
5 for j  1 to n2 -1
6 do R[j]  A[q + j+1]
7 L[n1]   Output: Merged sorted subarray in A[p..r].
8 R[n2]  
9 i0
10 j0
11 for k p to r
12 do if L[i]  R[j]
13 then A[k]  L[i]
14 ii+1
15 else A[k]  R[j]
16 jj+1
Merge – Example

A … 61 8
6 26
8 32
9 1
26 9
32 42 43 …

k k k k k k k k k

L 6 8 26 32  
R 1 9 42 43

i i i i i j j j j j
Comparing the Sorting Algorithms

Best Average Worst


Case Case Case
Bubble Sort O(n) O(n2) O(n2)
Insertion Sort O(n) O(n2) O(n2)
Selection Sort O(n2) O(n2) O(n2)
Merge Sort O(n log n) O(n log n) O(n log n)
Quick Sort O(n log n) O(n log n) O(n2)
Heap Sort O(n log n) O(n log n) O(n log n)

Das könnte Ihnen auch gefallen