3 | STACKS
A stack is a non-primitive Linear DATA structure. It is an ordered list in which addition
of NEW data item and deletion of already existing data is done from only one end, known as
TOP of the stack (TOS), As all the deletion and insertion in a stack is done from top of the
stack, the last added element will be the first to be removed. That is the reason, why stack is
also called Last In First Out.
Example : A common model of a stack is plates in a marriage, a party or coin stucker.
Fresh plates are “Pushed” onto the top and “popped” off the top.
Graphically we can represent this as follows :
o =| ap
(3)
oy | PP} as) Top} (20) (a3) Top
(20) (20)
(Empty Stack) "(Inserting) (inserting) “(nserting) (Element 54)
(Top) First Element” Second Element —_‘Third Element” Deleted
3.1 STACK IMPLEMENTATION
Stack can be implemented in two ways :
(a) Static Implementation
(6) Dynamic Implementation
(a) Static Implementation : Static implementation is done with the help of Array. In this
type memory is waste and this is not efficient.
(b) Dynamic Implementation : Is also called linked list representation, and uses pointers
to implement the stack type of Data structure.
3.2 OPERATIONS ON STACK
‘The basic operations that can be performed on stack are as follows :
1. Push : The process of adding a new element to the top of stack is called push
operation. Pushing an element in the stack invoke adding of element, as the new
(41)Data Structure Using ‘C”
element will be inserted at the top after every push operation, the top it
incremented by one. In case the array is full and no new element can
accommodated, it is called stack full condition. This condition is called stag,
overflow.
2. Pop : The process of deleting an element from the top of stack is called
operation. After every pop operation the stack is decremented by one. If there is ny
element on the stack and the pop is performed then this will result into stag
underflow condition.
3.3 STACK TERMINOLOGY
1. CONTEXT : The environment in which a function executes, includes argumeni
values, local variables and global variables. All the context except the global
variables is stored in a stack frame.
2. STACK frames : The data structures containing all the data (arguments, local
variables, return address ete.) needed each time a procedure or function is called,
3. MAXSIZE : This term is not a standard one, we use this term to refer the maximum
size of stack.
4. TOP : This term refers to the top of the stack (TOS). The stack top is used to check
stack overflow or underflow conditions. Initializing TOP stores -1.
5. STACK : It is an array of size MAXSIZE,
6. Stack empty or UNDERFLOW : This is the situation when the stack contains no
element. At this point the top of stack is present at the bottom of the stack.
1. Stack overflow : This is the situation when the stack becomes full and no more
elements can be pushed on to the stack. At this point the stack top is present at the
highest location of the stack.
3.4 ALGORITHMS FOR PUSH AND POP
1. Push : Let stack (maxsize] is an array for implementing the stack.
1. [check for stack overflow 1
if top = maxsize ~ 1 then print overflow and exit.
2. set top = top + 1[ increase the top by 1]
3. set stack [Top] = item [Inserts item in new top position]
4. Exit.
2, Algorithm for deleting an element from the stack : This algorithm deletes the
top element of the stack and assign it to a variable item.
1. [check for the stack UNDERFLOW]
if top <0 then
print “stack UNDERFLOW” and Exit.
else [Remove the top element]
set item = stack [top];
2. Decrement the stack top
set top = top - 1
3. Returned the deleted item from the stack.
4, ExitStacks EY
Problem : Write a program to demonstrate the following operations :
Push
Pop
Display
Enter your choice
Solution : #include
#include
#include
define MAX 10;
Void push ();
int pop;
int stack[maxsize};
Void display();
int top =-1;
Void main()
int ch;
char ch1;
do :
elrser();
printf(“\n 1 -» Push”);
printf{“\n 2 Pop”);
printf“\n 3 Display”);
printf(“\n Enter your choice”);
scanf(“%d”, &ch);
switch (ch)
{
ease 1: push();
break;
case 2: printf (“\n The deleted item is %d”, Pop);
break;
case 3: display();
break;
default : printf{“\n You entered wrong choice”);
}
printf(*\n Do you want to continue (Y/N )");
fflush(stdin);
scanfi“%c",&ch1);
while (ch1 == 'y’ | Ich1 == 'Y’);Data Structure Using C"
getch();
Void push()
int item;
if{top == maxsize ~ 1)
printf“\n Overflow stack is full”);
getch();
exit(0);
else
printf(“\n Enter the element which you want to insert”);
scanf(“%d”, &item);
top = top + 1;
stack{top] = item;
int pop()
inti;
if (top == -1)
printf(“\n UNDERFLOW stack is empty”);
getch();
exit(0);
else
i = stack[top];
top = top - 1;
}
return(i);
}
Void display()
t
inti
if (top == - 1)
printf(“\n stack is empty”);
getch();
exit(0);Stacks 25]
i che:
(
[ for(istop; i >= 0; i--)
(
printf(“\n The item is %d”, stack(i));
3.5 IMPLEMENTING STACK USING POINTERS
This is also known as linked list implementation of stack.
#include
#tinclude
struct stack
int no;
struct stack *next;
} *top = NULL;
typedef struck stack st;
void push();
int pop0;
void display();
void main()
(
int ch;
char chi;
int item;
do
{
clrser();
printf(“\n 1 > Push’);
printf(“\n 2 > Pop”);
printf(“\n 3 > Display”);
printf(“\n 4 + Exit”);
printf(“\n Enter your choice”);
scanf“%ed”, &ch);
switch(ch)
(
case 1: push();
break;
case 2: printf(“\n The deleted item is %d”, pop());
bre
| case 3: display();
break;Data Structure Using C
1
case 4: exit(1);
default : printf(“\n Wrong choice”);
printf(“\n Do you want to continue (Y/N)”);
flush(stdin);
scanf(“%e", &ch1);
while (ch1 == ‘y’ | | ch == ‘Y’);
getch();
void push()
st “node;
node = (st *) malloc (size of (st));
printf(“\n Enter the number “);
scanf(“%od”, & node -» number);
node — next = top;
top = node;
int pop()
st *temp;
printf(“\n Stack is empty”);
getch();
exit();
else
a
top = top -> next;
free(temp);
return(temp —> number );
void display()
st *temp;
temp = top;
while (temp —> next != NULL)
printf(“\n Number is %d”, temp -> ‘number );Stacks a
temp = temp —> next;
printf(“\n The number is %d”, temp > number );
1
3.6 APPLICATION OF STACKS
The following are the application of stack
As mentioned earlier, stack is one of the most commonly used data structures, some of
the applications are :
1. Stacks are used to pass parameters between functions. On a call to a function, the
parameters and local variables are stored on a stack.
2. High level Programming languages, such as Pascal , C ete. that provides support for
recursion use stack for book keeping. Remember, in each recursive call, there is
need to save the current values of parameters, local variables and the return
address (the address where the control has to return from the call).
3. Stack frames : Almost invariably, programs compiled from modern high level
languages (Even c!) make use of a stack frame for the working memory of each
procedure or function invocation.
4, When any procedure or functions is called, a number of words — The stack
frames — is pushed onto a program stack. When the procedure or function returns,
this frame of data is popped off the stack
5. As a function calls another function, first its arguments, then the return address
and finally space for local variables is pushed onto the stack. Since each function
runs in its own environment or context, it becomes possible for a function to call
itself — A technique is known as recursion. This capability is extremely useful and
extensively used — because many problems are elegantly specified or solved in a
recursive way.
NOTE : The stack is a region of main memory within which programs temporarily store dat
as they execute.
For example : When a program sends parameters to a function, the parameters are
placed on the stack. When the function completes its execution, these parameters
are popped off from the stack.
6. When a function calls other function the current contents (i.e., variables) of the
caller function are pushed onto the stack with the address of instruction just next to
the call instruction, this is done so that after execution of called function, the
compiler can track back (remember) the path frame where it is sent to the called
function.
7. Reversing a String : As the characteristic of stack is reversing the order of
execution. This fact can be exploited to reverse strings of line of characters. This can
be simply thought of simply as pushing the individual characters, and when the
complete line is pushed onto the stack, then individual characters of the line are
popped off, Because the last inserted character pushed on stack would be the first
character to be popped off, the line obviously be reversed.Data Structure Using ‘C’
{
3.7 CALCULATION OF POSTFIX EXPRESSION
Another application of stack, is calculation of postfix expression. To understand what is a
postfix expression. Let us undergo a discussion :
« There are basically three types of notation for an expression.
A. INFIX NOTATION —A+B
B. PREFIX NOTATION — + AB
C. POSTFIX NOTATION — AB +
Postfix notation is a type of notation which is most suitable for a computer to
calculate any expression (due to its reversing characteristic).
Postfix notation is the universally accepted notation for designing Arithmetic and
Logical Unit (A.L.U) and CPU (Processor).
Therefore it is necessary for us to study the postfix notation.
Moreover the postfix notation is the way computer looks towards any arithmetic
.
expression, any expression entered into the computer is first converted into postfix |
notation, stored in stack and then calculated.
3.7.1 Advantages of Using Postfix Notation
Although human beings are quite used to work with mathematical expressions in INFIX
NOTATION, which is rather complex, as using this notation one has to remember a set of |
non-trivial rules.
That set of rules must be applied to expressions in order to determine the final value.
These rules include precedence, BODMAS and Associativity.
Using INFIX NOTATION, one can't tell the order in which operators should be applied by
only looking at expression.
¢ Whenever an INFIX expression consists of more than one operators, the
precendence rules (BODMAS) should be applied to decide that which operator are
evaluated first.
¢ As compared to postfix notation, which is much more easy to work with or evaluate.
In a postfix expression, operands appear before the operators, there is no need for
operator precedence and other rules.
‘¢ As soon as an operator appears in the postfix expression, during scanning of postfix
expression, the topmost operands are popped off and are calculated applying the
encountered operator. Place the result back onto the stack, doing so the stack will
contain finally a single value at the END of PROCESS.
3.8 NOTATION CONVERSION
Let us expression A + B * C is given in, which is in infix notation. To calculate this
expression for the values 4, 3, 7 for A, B and C respectively we must follow certain rules
(called BODMAS in general mathematics) in order to have right result.
For example: A+B*C=4+3*7=7*7=49
Is this the right result ? No, this is because the multiplication is to be done before
addition, because it has higher precedence over addition,[ Stacks | 29]
The error in the above calculation oceurs, as there are no braces to define the precedence
of operators. Thus expression A + B * C is interpreted as A + (B * C). This is an alternative to
convey the computer that multiplication has higher precedence over addition, as there is no
other way to specify this,
Operator Precedence :
Exponential operator Highest precedences
Multiplication/division +,! Next precedence
Addition/substraction +, Least precedence
3.8.1 Rules for Converting Infix to Postfix Form
1. Parenthesize the expression starting from left to right. .
2. During parenthesizing the expression, the operands associated with operator
having higher precedence are first parenthesized. :
3. The sub-expression (part of expression) which has been converted into postfix is to
be treated as single operand. :
4. Once the expression is converted to postfix form, remove the parenthesize.
For example
1. A+Bte (Convert this into postfix)
A+(B*0)
A+(BC*)
(ABC *+) Ans.
2. A+[(B+C)+(D+E)*FVG
A+ [i (BC+) + (DE+) * FG]
A+ (| (BC+) +(DE+F * GI
A+ | (BC+) (DE +F * #)/G]
A+([BC+DE+F*+G/
ABC +DE+F*+G/+ Ans.
Example: A+B-C
(A+B)-C
(AB +)-C
AB+C- Ans.
Example: A*B+C/D
(A*B)+(CD)
(AB *) + (CD)
AB* CD/+ Ans.
Example: A *B+C
=> (A*B)+C
(AB *) +C *
=> AB*C+ Ans.
Example: A+B/C-D
A+(BIC)-D
A+(BC/+)-D
(ABC /+D-) Ans. fB Data Structure Using ‘C
Example» (A+ BY(C-D)
[AB+/(CD-]
AB+CD~/ Ans.
Example: (A+B)* C/D
(AB+) * C/D
(AB + CD
(AB+C*D/) Ans.
Example: [A+B]*C/D+Ba F/G.
(AB+]*C/D+ EA F/G.
[AB+]*C/D+ (BA F)/G
[AB+]*C/D+ (EFa)/G
[AB+C*] /D+(EFA)/G
[AB+C+D]+[EFAG/]
AB+C*D/ EFAG/+ Ans.
3.8.2 Algorithm for Converting infix Expression to Postfix form Postfix (Q, P)
Suppose Q is an arithmetic expression written in Q INFIX NOTATION. This algorithm
finds the equivalent postfix expression P.
Push “(“ Onto stack and add ”)” to the end of Q.
Scan Q from left to right and repeat steps 3 to 6 for each statement of Q until the
stack is empty.
Non
2
If an operand is encountered, add it top.
If a left parenthesis is encountered, push it onto the stack.
ae
If an operator x is encountered then
a. Add x to stack
(end of it structure)
b. Repeatedly pop from stack and add P each operator (on the top of stack) which
has the same precendence as or higher precedence than x.
Ifa right parenthesis is encountered then
a. Repeatedly pop from stack and add top each operator (on the top of stack until
a left parenthesis is encountered).
b. Remove the left parenthesis (Do not add the left parenthesis top).
2
(End of step 2 loop).
7. Exit
Note : In the infix to postfix conversion algorithm, x means any of the operator.
Problem : Write a program to convert an infix expression into an equivalent postfix
expression
Solution : #include
#includeStacks Bs]
#includecstring.h>
char stack{50];
int top=-1;
Void in_to_post (chart ]);
Void push (char);
char pop();
int preced (char);
Void main()
or Void in_to_post (char *);
char infix(50];
printf(“\n Enter the infix expression”);
geta(infix);
in_to_post (infix);
getch();
Void push(char symb)
if (top >= 49)
printf(“\n Stack overflow”);
getch0);
return();
top = top +1;
stack{top] = symb;
char pop()
printf(“\n Stack is empty”);
getch();
return();
!
else
item = stack{top];El Data Structure Using ‘©
~
top--;
1
return(item);
I
int preced (char ch) if (ch ==‘)
{ {
return 5;
{ OR }
else if (ch == “*"| Ich
| return 4;
else if (ch == ‘+’ || ch =
return
else
} return 2;
}
return (4);
else if (ch
return (3);
else
return (2);
i
void in_to_post (char infix{ ])
int length;
static int index = 0, pos = 0;
char symbol, temp;
char postfix(50);
length = strlen(infix);
while(index < length)
symbol = infix(index);
switch(symbol)
Push (symbol);
break;
temp = pop ();
while(temp !=’
postfix[pos] = temp;
pos +4;
temp = pop();= preced (symbol))
(
temp = pop(); post fix [pos] = symbol;
postfix (pos) = temp; Post+
Pos +4;
)
push (symbol);
break;
default : Postfix{pos++] = symbol;]
break; post fix [pos] = temp;
! post++
index +4;
while(top >= 0)
temp = pop();
Postfix[pos++] = temp;
postfix[pos++]
puts(postfix);
return;
0’;
}
3.8.3 Converting Infix Expression to Prefix Expression
This algorithm is bit tricky, in this we first reverse the input expression a + b*e will
become c*b + a and then we do the conversion and then again we reverse to get the result.
Doing this has an advantage that except for some minor modification algorithm for infix to
prefix remains almost same as the one for infix to postfix.
Example: A+B*C (C*B+A)
(C*B)+A
(CB*) +A
C(B*A+)
(+A*BC) Ans.
Algorithm and program is same but only the difference is that firstly we reverse the
given string and then evaluate it and then we again reverse it.Data Structure Using‘
Problem : CONVERT A + (B * C - (D/E - F) * @) * H into postfix form showing uy,
status after every step in tabular form
Solution : (A +(B * C-(D/B- F)* G)* H)
S.No.| Symbol | Stuck Expression
Es ( ¢
2. A ¢ A
3. + G A
4 C+ A
e B (4 AB
B * He AB
1 c Ge ABC
2 = Ge ‘ABC*
9. ( HH ‘ABC*
10.|__D (HH ‘ABC*D
ll. i (cso ABC*D.
12. E (m7 ABC*DE
13. S He ABC*DE/
14, E Gee ABC*DE/F
15. |+ Ge ABC*DE/F-
16. * Ot ABC*DE/F-
17. G Ge ABC*DE/F-G
18. ) G ABC*DE/F-G*-
19. . Gt ABC*DE/F-G*—
20, H Ga ABC*DE/F-G*-H_
21. ) ABC*DE/F-G*-H*+
Problem : Give postfix form of expression for the following :
Not A OR Not B Not C
Solution : The order of evaluation will be
((Not A) OR (Not B) AND (Not C))
# ((A Not) OR (B Not) AND (C Not))
« ((A Not) OR (B Not C Not AND)
« ANot B Not C Not AND OR
3.8.4 Algorithm to Evaluate a Postfix Expression
This algorithm finds the value of an arithmetic expression P written in postfix notation.
The following algorithm, which uses a stack to hold operands, evaluates P.
Algorithm :
1. Add a right parenthesis ‘Y at the end of P. (This act as a sentinel].
|
|c7 Stacks Ass]
2. Scan P from left to right and repeat steps 3 and 4 for each statement of P until the
sentinel ‘) is encountered,
8. Ifan operand is encountered, put it on stack.
4. Ifan operator x is encountered then
(a) Remove the two top elements of stack, where A is the top element and B is
next to top element.
(6) Evaluate B xA
(©) Place the result of (b) back on stack.
(End of it structure]
(End of step 2 loop]
5. Set value equal to the top element on stack.
6. Exit.
Problem : Evaluate the postfix expression
AB+C*D/ ifA=2,B=3,C=4andD=5.
Solution : (23 + 4 * 5)
Step 1 : First element 2 push onto the stack.
Step 2 : Second element 3 push onto the stack.
3
2 2
Step 3 : Now operator + is encountered.
Step 4 : Push onto the stack.
| 4
| 5 5
Step 5 : Now operator * is encountered.
Step 6 : Now 5 push onto the stack.
step 7: 1 is encountered and the final result is 4.
20 20BE Data Structure Using
Problem : Evaluate the expression
562 +* 124 | ~in tabular form showing stack after every step.
Solution :
Step Input Symbol/Element Stack Output
(If creates)
1 ® Push ©
2 © Push ©®
3 @ Push ©6.@
4 @ Pop @) elements ® ®
5 Push result
6 © Pop 2 elements #, empty 5x8=40
7 Push result 40
8 12 Push 12 40, 12
9 4 Push Y 40, 12,4
10 ! Pop two elements 124 =-@
i Push result @)
12 oa Pop two element Em pty, # @
Push result @7) @ @ resutt
Problem : Write a program to accepts a postfix expression, asks the values for variables
of the expression, calculate the expression for that values.
Solution :
abe *+
abe *+
231 *+
#include
#include
float stack(10);
int top = —1;
Void push(float);
float pop0;
float level(chart }, float{ });po
Stacks m7]
void main()
int i=0;
char suffix(20};
float value(20), result;
clrser();
printft"\n Enter a valid postfix expression”);
gets(suffix);
while(suffixtil
‘\0")
{
iftisalpha (suffixli))
(
flush(stdin);
printf{“\n Enter the value of %e”, suffixli));
scanft“%ef”, &valueli));
ies;
result = eval (suffix, value);
printi(“The result of %s = %f", suffix, result);
getch();
float eval(char suffix[ J, float datal ])
inti=0;
float op, op2, res;
char ch;
while (suffix{i] != ‘\0")
ch © suffixli];
if (is alpha (suffix [i)))
Push (data [i));
else
op2 = pop();
op1 = pop();
switch (ch)
case ‘+’: push (op1 + op2);
break;
case’: push (opl ~ op2);
break;case’: push (op * op2);
break;
case? push (op1 / op2);
break;
case‘,’: push (opl , op2); |
break;
itt;
}
res = pop();
réturn(res);
Void push(float num)
top = top + 1;
stack [top] = num;
}
float pop()
float num;
num = stack{top]};
top = top — 1;
return(num);
1
3.9 PARENTHESIS CHECKER
Output is as follows :
Enter a valid postfix expression ab+
Enter the value of a— 8
Enter the value of b — 8
The result of ab + is
=> 16.000000
Parenthesis checker is a program that ‘checks whether a mathematical expression, is
properly parenthesized.
We will consider three sets of grouping symbols :
« The std. parenthesis ()
The braces — {)
« The brackets — [ ]
For a input expression, it verifies that for each left parenthesis brace, or bracket, there is
a corresponding closing symbol and the symbols are appropriately nested.
Some examples of valid inputs
Some examples of invalid inputs
QO
CO
Cty)
0)
cog)
aug)— ———_——
—
Le
| 3,9.1 Algorithm for Parenthesis Checker
. Parenthesis checker (exp)
Here exp is a character string representing an arithmetic expression comprising all types
of bracketing symbols.
begin
read expression
for each character C in exp.
if (current symbol or character is a left symbol) then
push the character onto the stack
else if{current symbol is a right symbol) then
if (stack is empty) then
print(“Error no matching open symbol”);
exit
else
pop a symbol s from the stack.
if (s does not correspond to ¢) then
printf “Error incorrect nesting of symbols”
exit
end if
end if
end if
end for
if (stack is not empty) then
print “ Error missing closing symbol ”.
else
print “ Input expression is OK”
end ifend
3.10 QUICK SORT ALGORITHM
Quick sort is an algorithm that uses devide and conquer strategy to SORT AN ARRAY. In
the devide and conquer strategy, the problem to be solved is devided into two subproblems,
which are then solved separately. Then the solutions of these two subproblems are combined
to generate the solution of the given problem.
Quick SORT method reduces the problem of sorting a set of number to the problem of
sorting two subsets of smaller size.
‘This reduction step is illustrated below with the help of an example.
Consider the following list of 8 numbers
20, 22, 15, 10, 35, 12, 44, 38
The reduction step of quicksort algorithm finds the final position of the first number , 20
in this case.PEG date Structure Usin
This is accomplished as follows :
20, 22, 15, 10, 35, 12, 44, 38
Beginning with the right most(last) number, 38 scan the list from right to left, comparing
each number with 20 and stopping at the first number less than 20. The number is 12.
Interchange 20 and 12 to obtain the following list :
12, 22, 15, 10, 88, 20, 44, 38
Now beginning with 12, scan the list from left to right comparing each number with 20
and stopping at the first number greater than 20. The number is 22 interchange 22 and 20,
‘To obtain the list.
12, 20, 15, 10, 35, 22, 44, 38,
Now beginning with 22, scan the list from right to left comparing each number with 20
and stopping at the first no less than 20, the number is 10, interchange 10 and 20. To obtain
the list.
12, 10, 15, 20, 35, 22, 44, 38,
Now beginning with 10, scan the list from left to right, comparing each number with 20,
and stopping at the first number greater than 20. We do not meet any such number before
meeting 20. This means all the numbers have been scanned and compared with 20.
“Further all the numbers less than 20 now form the sublist of numbers to the left of 20,
and all numbers greater than 20 now form the sublist of numbers to the right of 20 as shown
below :
12, 10, 15, , 4 4
(Left sublist) (Left sublist)
Thus, element 20 is correctly placed in its final position, and the task of sorting the
entire list is now reduced to sorting two sublists of smaller size.
The above reduction step is repeated with each sublist containing two or more
elements.
Since we can process one list at a time, we must keep track of the other sublist for
future processing.
‘This is accomplished by using a stack with integer elements to temporarily hold
these sublists.
‘That is the index of the first element and index of the last element of each sublist
are pushed onto the stack.
The reduction step is applied only once these indices are removed from the stack.
Problem : Write a program to demonstrate the use of stack in implementing Quick sort
algorithm to sort an array of integers in ascending order.
Solution : #includecstdio.h>
#include
#include|
|
Stacks Ey
#includecalloc.h>
#define MAX 20;
typedef struct node
int info;
struct node*next;
}
stack;
typedef enum(false, true} boolean;
Void createstack(stack*);
boolean is empty(stack };
Void push(stack *, int);
int pop(stack *);
Void disposestack(stack *);
Void reduction (int *, int, int, int);
Void quicksortiterative(int *, int);
Void main()
int i, n, almax};
elrser();
printf(“\n Enter number of elements in Array”);
seanf(“%d”, &n);
ifn > max)
printf(“\n Input size of ARRAY greater than declared size”);
exit(L);
printf(“\n Enter %d elements”, n);
printf(“\n Enter the elements”);
seanf(“%d", &ali));
quicksortiterative(a,n);
printf(“\n Sorted list of elements are”);
for(i=0; ic n; i++)
printf(“\n%d”, ali);
getch);
Void push(stack *top, int value)——
a Data Stuctur Using © SSS
stack *p;
P= (stack *) malloc (nize offatack));
itp == NULL)
printf("\n Unable to allocate memory for new node”), t
printf{"\n Press any key to exit”);
getch();
return;
P > info = value;
P > next = top;
top = p;
int pop (stack *top)
int ty
stack *P;
t= top + info;
P = top;
top = top -> next;
free(p);
return t; }
Void create stack (stack *top) ‘
top = NULL;
boolean is empty (stack *top)
if top == NULL)
return true;
else
return false;
1
Void dispose stack (stack *top)
\
stack *p; |
while(top != NULL)
i
P= top;
top = top -+ next
free(p);Stacks
Void reduction (int *a, int beg, int end, int loc)
(
int loft, right, temp;
boolean done;
left = loc = beg;
righ
done = falso;
while (!done)
i
while ((afloc] < afright]) && (loc != right))
right- -;
if (loc == right)
done = true;
else
temp = alloc];
alloc] = alright];
afright] = temp;
loc= right;
}
if (!done)
while((afloc] > afleft]) && (loc != left))
left +45
if (loc == left)
temp = alloc];
alloc] = afleft};
alleft] = temp;
loc = left;
) /*End of else*/
} /*End of if */
) /* End of while*/
} /* End of function */
Void quicksort iterative (int “a, int n)
{
int loc, beg, end;
stack top;
createstack (top);
push (top, 0);
push (top, n—1);[EET bate Structure Using
while (! is empty (top))
end = pop(top); 1
beg = pop(top); |
reduction(a, beg, end, loc);
ifbog < loc-1)
push(top, beg);
push(top, loc - 1);
if (end > loc +1)
push (top, loc +1;
Push (top, end);
)
| End of while*/
) /*End of function*/
SUMMARY
Stack is a Linear Data Structure, which holds the Last in First out property. |
In stack, two functions are there (1) push (2) pop.
Push is used to insert any element in the stack.
Pop is a function which is used to delete the top most element.
We use the stack in various fields for example,
Stack is used to convert the infix expression into postfix form.
Stack is used to evaluate the postfix expression. |
Stack is used to implement the Quick Sort Algo interactively. |
Stack is also used in zero Address Instruction in Microprocessor.
‘The main important use of stack is done in computer.
Write a program to implement push and pop function using array ?
|
PRosBLEmMsS :
Sr
Write a program to implement the linked stack ?
Why stack is called a LIFO Data Structure ?
List the applications of stack in computer ?
Write a program to input an infix expression andconvert it into prefix form ?
Explain the following terms :
(a) Infix expression (b) Polish notation (c) Reverse polish notation
7. Differentiate between prefix and postfix expressions ?
erase10,
1.
12,
13,
14.
Write @ program to input an expression and check whether it is property parenthesized or
not ?
Evaluate the expression 6 62 +* 12 4/~ in Tabular form showing stack after every step,
Convert the following infix expression to their equivalent postfix expressions ?
() A-B/C (b) (A* B) #(C~D)
fe) (ABYC) + D (d) AABAC#D
‘Transform the above expression to their prefix form.
Evaluate the following postfix expressions
(a) 987% + (b) 40.25 +206 *3+
(c) 21188 A/9+ (d) 764+4*4/0-A 5+
Write a program to input a string and print the reverse of the string with the help of stack ?
Define the application of stack in computers ?