0% found this document useful (0 votes)
4 views

4. Stack

hehheee

Uploaded by

dpatelbe22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

4. Stack

hehheee

Uploaded by

dpatelbe22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

UCS301 - Data Structures and Algorithms

Stack

Department of CSE
Thapar Institute of Engineering and Technology, Patiala
Introduction
• Non primitive linear
data structure. Data Element n TOP
• Allows operations at …
one end only. …
• The top element can …
only be accessed at Data Element 3
any time. Data Element 2
– LIFO (Last-in-first-
Data Element 1
out) data structure.
2
Operations
• Two primary operations:
– push() − Pushing (storing) an element on the stack.
– pop() − Removing (accessing) an element from the
stack.
• Other operations for effective functionality:
– peek() − Get the top data element of the stack,
without removing it.
– isFull() − Check if stack is full. OVERFLOW
– isEmpty() − Check if stack is empty. UNDERFLOW
3
Stack – Push
push(9) push(1) push(3) push(6) push(4) push(2)

9 1 3 6 4 2
top = 4
4 4 4 4 4 top 4 4 4 4

3 3 3 3 top 6 3 6 3 6 3

2 2 2 top 3 2 3 2 3 2 3 2

1
top 1 1 1 1 1 1 1 1 1 1
1
top 9 0 9 0 9 0 9 0 9 0 9 0
0
top = -1 OVERFLOW

The stack is full, no more elements


can be added. OVERFLOW
4
Stack – Pop
pop() pop() pop() pop() pop() pop()

4 6 3 1 9 Nothing
top = 4
4 4 4 4 4 4 4 4
6 3 top 6 3 3 3 3 3 3
3 2 3 2 top 3 2 2 2 2 2
1 1 1 1 1 1 top 1 1 1 1 1
9 0 9 0 9 0 9 0 top 9 0 0 0

top = -1 top = -1
UNDERFLOW

The stack is empty, no element


can be removed. UNDERFLOW
5
Stack as an ADT
• A stack is an ordered list of elements of same data
type.
• Elements are always inserted and deleted at one
end.
• Following are its basic operations:
– S = init() – Initialize an empty stack.
– isEmpty(S) – Returns "true" if and only if the
stack S is empty, i.e., contains no elements.
6
Stack as an ADT
– isFull(S) – Returns "true" if and only if the
stack S has a bounded size and holds the maximum
number of elements it can.
– top(S) – Returns the element at the top of the
stack S, or error if the stack is empty.
– S = push(S,x) – Push an element x at the top of the
stack S.
– S = pop(S) – Pop an element from the top of the
stack S.
– print(S) – Prints the elements of the stack S from
top to bottom.
7
Implementation
• Using static arrays
– Realizes stacks of a maximum possible size.
– Top is taken as the maximum index of an
element in the array.
• Using dynamic linked lists
– Choose beginning of the list as the top of the
stack.
8
Using Static Arrays
Algorithm for Push
• Let,
– STACK[SIZE] is a one dimensional array that will hold
the stack elements.
– TOP is the pointer that points to the top most element
of the stack.
– DATA is the data item to be pushed.
1. If TOP == SIZE – 1
2. Display "Overflow condition"
3. Else
4. TOP = TOP + 1
5. STACK [TOP] = DATA
10
Algorithm for Pop
• Let,
– STACK[SIZE] is a one dimensional array that will hold the
stack elements.
– TOP is the pointer that points to the top most element of
the stack.
– DATA is the element popped from the top of the stack.
1. If TOP < 0 (or TOP == -1)
2. Display "Underflow condition."
3. Else
4. DATA = STACK[TOP]
5. TOP = TOP – 1
6. Return DATA
11
Static Array Implementation
1. #define MAXLEN 100 9. int isEmpty ( stack S )
10. { return (S.top == -1); }
2. typedef struct
3. { int element[MAXLEN]; 11. int isFull ( stack S )
4. int top; } stack; 12. { return (S.top == MAXLEN - 1);
}
5. stack init ()
6. { stack S; 13. int top ( stack S )
7. S.top = -1; 14. { if (isEmpty(S))
8. return S; } 15. printf("Empty stack\n");
16. else
17. return S.element[S.top]; }

12
Contd…
18. stack push ( stack S , int x )
19. { if (isFull(S))
20. printf("OVERFLOW\n");
21. else
22. { ++S.top;
23. S.element[S.top] = x; 25. stack pop ( stack S )
24. } 26. { if (isEmpty(S))
25. return S; } 27. printf("UNDERFLOW\n");
28. else
29. { --S.top; }
30. return S; }

13
Contd…
31. void print ( stack S )
32. { int i;
33. for (i = S.top; i >= 0; --i)
34. printf("%d",S.element[i]); }

35. int main () 42. printf("Current stack : ");


36. { stack S; 43. print(S);
37. S = init(); 44. printf(" with top = %d.\n", top(S));
38. S = push(S,10); 45. S = pop(S);
39. S = push(S,45); 46. S = pop(S);
40. S = push(S,1); 47. printf("Current stack : ");
41. S = push(S,50); 48. print(S);
49. printf(" with top = %d.\n", top(S));
50. return 0; }
14
Algorithm for Push
• Let,
– TOP is the pointer that points to the top most
element of the stack.
– DATA is the data item to be pushed.
1. Create a node pointer (newNode).
2. newNode[data] = DATA.
3. newNode[next] = top.
4. top = newNode.
15
Algorithm for Pop
• Let,
– TOP is the pointer that points to the top most element
of the stack.
– temp points to the element popped from the top of the
stack.
1. If (TOP == NULL)
2. Print [Underflow condition].
3. Else
4. initialize a node pointer (temp) with TOP.
5. TOP = TOP[next]
6. Release the memory location pointed by temp.
7. end if
16
Applications
• Reverse a word.
– Push a word letter by letter and then pop letters from
the stack.
• "UNDO" mechanism in text editors.
• Backtracking.
– Game playing, finding paths, exhaustive searching.
• Parsing.
• Recursive function calls.
• Calling a function.
• Expression Evaluation.
• Expression Conversion.
17
Expression Representation
• Infix – Operator is in-between the operands.
• Prefix – Operator is before the operands. Also
known as polish notation.
• Postfix – Operator is after the operands. Also
known as suffix or reverse polish notation.
Infix Prefix Postfix
a+b +ab ab+
a+b*c +a*bc abc*+
(a + b) * (c - d) *+ab-cd ab+cd-*
18
Example (Infix to Postfix)
• 5+3*2
• 532*+
• 3+4*5/6
• 345*6/+
• ( 300 + 23 ) * ( 43 – 21 ) / ( 84 + 7 )
• 300 23 + 43 21 - * 84 7 + /
• (4+8)*(6–5)/((3–2)*(2+2))
• 48+65-*32–22+*/
19
Infix to Postfix Conversion Algorithm
• Let Q be any infix expression to be converted in to a postfix expression P.
1. Push left parenthesis onto STACK and add right parenthesis at the end of Q.
2. Scan Q from left to right and repeat step 3 to 6 for each element of Q until
the STACK is empty.
3. If an operand is encountered add it to P.
4. If a left parenthesis is encountered push it onto the STACK.
5. If an operator is encountered, then
i. Repeatedly pop from STACK and add to P each operator which has same
precedence as or higher precedence than the operator encountered.
ii. Push the encountered operator onto the STACK.
6. If a right parenthesis is encountered, then
i. Repeatedly pop from the STACK and add to P each operator until a left
parenthesis is encountered.
ii. Remove the left parenthesis; do not add it to P.
7. Exit
20
Input Stack Output
A + (B * (C – D) / E)
A + (B * (C – D) / E)) (
+ (B * (C – D) / E)) ( A
(B * (C – D) / E)) (+ A Input Stack Output
B * (C – D) / E)) (+( A – D) / E)) (+(*( ABC
* (C – D) / E)) (+( AB D) / E)) (+(*(– ABC
(C – D) / E)) (+(* AB ) / E)) (+(*(– ABCD
C – D) / E)) (+(*( AB / E)) (+(* ABCD–
E)) (+(/ ABCD–*
)) (+(/ ABCD–*E
) (+ ABCD–*E/
ABCD–*E/+
Infix to Prefix Conversion Algorithm
• Reverse the given expression.
• Apply algorithm for infix to postfix conversion.
• Reverse the expression.

22
Example
• (A+B^C)*D+E^5
1. Reverse the infix expression.
5^E+D*)C^B+A(
2. Make Every '(' as ')' and every ')' as '('
5^E+D*(C^B+A)
3. Convert expression to postfix…

23
Input Stack Output

5 ^ E + D * (C ^ B + A)
5 ^ E + D * (C ^ B + A)) (
^ E + D * (C ^ B + A)) ( 5
Input Stack Output
E + D * (C ^ B + A)) (^ 5
A)) (+*(+ 5E^DCB^
D * (C ^ B + A)) (+ 5E^
)) (+*(+ 5E^DCB^A
* (C ^ B + A)) (+ 5E^D
) (+* 5E^DCB^A+
(C ^ B + A)) (+* 5E^D
5E^DCB^A+*+
C ^ B + A)) (+*( 5E^D
^ B + A)) (+*( 5E^DC 4. Reverse the expression.
B + A)) (+*(^ 5E^DC +*+A^BCD^E5
+ A)) (+*(^ 5E^DCB
Example (Infix to Prefix)
• 5+3*2
• +5*32
• 3+4*5/6
• +3*4/56
• ( 300 + 23 ) * ( 43 – 21 ) / ( 84 + 7 )
• * + 300 23 / – 43 21 + 84 7
• (4+8)*(6–5)/((3–2)*(2+2))
• *+48/–65*–32+22
25
Postfix Evaluation Algorithm
1. Initialize empty stack
2. For every token in the postfix expression (scanned from left to right):
a. If the token is an operand (number), push it on the stack
b. Otherwise, if the token is an operator (or function):
i. Check if the stack contains the sufficient number of values
(usually two) for given operator
ii. If there are not enough values, finish the algorithm with
an error
iii. Pop the appropriate number of values from the stack
iv. Evaluate the operator using the popped values and push the
single result on the stack
1. If the stack contains only one value, return it as a final result of the
calculation
4. Otherwise, finish the algorithm with an error
26
Example
• Evaluate 2 3 4 + * 6 –
• 2 * (3 + 4) - 6 = 8.

27
Input Operation Stack contents Details
token (top on the right)
234+*6– 2 Push on the stack 2
34+*6– 3 Push on the stack 2, 3
4+*6– 4 Push on the stack 2, 3, 4
+*6– + Add 2, 7 Pop two values: 3 and
4 and push the result
7 on the stack
*6– * Multiply 14 Pop two values: 2 and
7 and push the result
14 on the stack
6- 6 Push on the stack 14, 6
- - Subtract 8 Pop two values: 14
and 6 and push the
result 8 on the stack
(End of (Return the 8 Pop the only value 8
tokens) result) and return it
Thapar University UCS406 - Data Structures and Algorithms 32
Solve
• Consider the following Stack , where STK is
allocated N=6 memory cells:
STK: PPP,QQQ, RRR,SSS,TTT
Describe the stack as the following operations take
place:
1. PUSH(STK, UUU)
2. POP(STK)
3. PUSH(STK, VVV)
4. PUSH(STK, WWW)
5. POP(STK)
29
Solve
•Convert to equivalent postfix expression:
1.(A-B)*(D/E)
2. A*(B+D)/E-F*(G+H/K)
3. ((p+q)*s^(t-u))

• Evaluate the expression 5 6 2+*12 4 /- in tabular


form showing stack after every step.

30
Postfix to Infix Conversion Algorithm
1. Accept a postfix string from the user (say P).
2. Start scanning the string one character at a time.
3. If it is an operand, push it in stack.
4. If it is an operator, pop opnd1, opnd2 and
concatenate them in the order "(opnd2, optr,
opnd1)".
5. Push the result in the stack.
6. Repeat these steps until input postfix string P ends.
7. Pop the remaining element of the stack, which is the
required Infix notation equivalent to a given Postfix
notation.
31
Solve: abc-+de-fg-h+/*
Expression Input token Stack contents as strings (top on the right)
abc-+de-fg-h+/*
bc-+de-fg-h+/* a a
c-+de-fg-h+/* b a, b
-+de-fg-h+/* c a, b, c
+de-fg-h+/* – a, (b – c)
de-fg-h+/* + (a + (b – c))
e-fg-h+/* d (a + (b – c)), d
-fg-h+/* e (a + (b – c)), d, e
fg-h+/* – (a + (b – c)), (d – e)
g-h+/* f (a + (b – c)), (d – e), f
-h+/* g (a + (b – c)), (d – e), f, g
h+/* – (a + (b – c)), (d – e), (f – g)
+/* h (a + (b – c)), (d – e), (f – g), h
/* + (a + (b – c)), (d – e), ((f – g) + h)
* / (a + (b – c)), ((d – e) / ((f – g) + h))
Thapar University UCS406 - Data Structures and Algorithms 36
* ((a + (b – c)) * ((d – e) / ((f – g) + h)))
Prefix to Infix Conversion Algorithm
1. Accept a prefix string from the user (say P).
2. Start scanning the string from right one character at a
time.
3. If it is an operand, push it in stack.
4. If it is an operator, pop opnd1, opnd2 and concatenate
them in the order "(opnd1, optr, opnd2)".
5. Push the result in the stack.
6. Repeat these steps until input prefix string P ends.
7. Pop the remaining element of the stack, which is the
required Infix notation equivalent to a given Prefix
notation.
33
Example
• Solve: *+a-bc/-de+-fgh
• We can either start scanning from right or reverse
the expression first and then scan from left to
right.
• The reversed expression is
hgf–+ed–/cb–a+*

34
Expression Input token Stack contents as strings (top on the right)
hgf–+ed–/cb–a+*
gf–+ed–/cb–a+* h h
f–+ed–/cb–a+* g h, g
–+ed–/cb–a+* f h, g, f
+ed–/cb–a+* – h, (f – g)
ed–/cb–a+* + ((f – g) + h)
d–/cb–a+* e ((f – g) + h), e
–/cb–a+* d ((f – g) + h), e, d
/cb–a+* – ((f – g) + h), (d – e)
/cb–a+* / ((d – e) / ((f – g) + h))
b–a+* c ((d – e) / ((f – g) + h)), c
–a+* b ((d – e) / ((f – g) + h)), c, b
a+* – ((d – e) / ((f – g) + h)), (b – c)
+* a ((d – e) / ((f – g) + h)), (b – c), a
* + ((d – e) / ((f – g) + h)), (a + (b – c))
* ((a + (b – c)) * ((d – e) / ((f – g) + h)))
35
Using Dynamic Linked Lists
Dynamic Linked List Implementation
1. struct Node
2. { 8. void push(int value)
3. int data; 9. {
4. struct Node *next; 10. struct Node *newNode;
5. }*top; 11. newNode = (struct
Node*)malloc(sizeof(struct Node));
6. void init() 12. newNode->data = value;
7. { top = NULL;} 13. if(top == NULL)
14. newNode->next = NULL;
15. else
16. newNode->next = top;
17. top = newNode;
18. }
37
Contd…
19. void pop()
20. {
21. if(top == NULL)
22. printf("\nUnderflow\n");
23. else{
24. struct Node *temp = top;
25. printf("\nDeleted element: %d", temp->data);
26. top = temp->next;
27. free(temp);
28. }
29. }

38
Contd…
30. void display()
31. {
32. if(top == NULL)
33. printf("\nStack is Empty!!!\n");
34. else{
35. struct Node *temp = top;
36. while(temp->next != NULL){
37. printf("%d--->",temp->data);
38. temp = temp -> next;
39. }
40. printf("%d--->NULL",temp->data);
41. }
42. }
39

You might also like