Ds Module 2 Notes22
Ds Module 2 Notes22
It is a linear data structure or ordered collection of elements where the elements are processed in last in first
out manner(LIFO).
In stack insertion and deletions are made at one end i.e top
Stack can be implemented by using array or linked list
Operations on stacks.
Special terminology is used for two basic operations associated with stacks are,
a.PUSH operation.
40
30 30
20 20 20
10 10 10 10
top=-1 top=0 top=1 top=2 top=3
when stack is empty after inserting 10 after inserting 20 after inserting 30 after inserting 40
(Stack is overflow)
When top=-1 stack is empty i.e there are no elements in the stack
After inserting first element top is incremented to 1st position(0th index)of stack
Similarly top will get increment BY ONE after inserting every element in to stack
When top value become MAXSTK-1(where MAXSTK is maximum number of elements that stack can
have) stack is full that condition is called as stack overflow.
b.POP operation.
40
30 30
20 20 20
10 10 10 10
top=3 top=2 top=1 top=0 top=-1
when stack is full after deleting 40 after deleting 30 after deleting 20 after deleting 10
(Stack is underflow)
If top ≠ -1 the top element of stack is deleted, otherwise stack is empty
When an element of the stack is deleted top get decremented by one
When top=-1 stack will become empty and that condtion is called stack underflow
Array Representaion of stacks:
Stacks may be represented in the computer in various ways,normally by using linear array or
Linked list.
Unless we specified or stated ,each of our satcks will be maintained by a linear array STACK.
A pointer variable TOP ,which contains the location of the top element in the stack
And a variable MAXSTK which gives the maximum number of elements that can STACK
have.
The condition TOP=-1 or TOP=NULL will indicate that the stack is empty
10 20 30 40 50
0 1 2 3 4 5 6 7
The above array can be used to perform stack operations like push and pop
When a stack is implemented by using static arrays the size of the stack is bound to
MAXSTK(i.e maximum elements a stack can have)but some time stack need be dynamic.
This can be achieved by using dynamic arrays
The memory for the stack is dynamically allocated by using memory allocation functions such
as malloc or calloc
When the stack is full , memory of the stack is doubled by using realloc() function
and the capacity of the stack is doubled(MAXSTK is doubled)
void display()
{
int i;
if(top==-1)
{
printf(“stack is empty \n”);
Return;
}
for(i=top;i>=0;i--)
printf("%d",*(stack+i));
}
void main()
{
int choice=1;
stack=malloc(capacity*sizeof(int));//allocating memory dynamically
while(choice)
{
printf("enter your choice\n 1.push\n 2.pop\n 3.display \n 4 exit\n");
scanf("%d",&choice);
switch(choice)
{
case 1:push();
break;
case 2:pop();
break;
case 3:display();
break;
case 4:printf("invalid operation\n");
exit(0);
}
}
free(stack);// deallocating memory
stack=NULL; //avoiding dangling pointer
}
In the above implementation the function stackfull() doubling the size and memory of the stack.
Applications of stacks:
Stack is used to convert expressions .ex: infix to postfix.
Stack can be used to evaluate the expressions
During function call stack is used
Arithmatic Expressions:
An expression is a one which is a combination of meaning full Arithmatic opeartors and operands.
The prcedence levels of the Arithmatic opeartors as follows.
Highest: Exponentiation( )or(^)
Next Highest: Multiplication(*) , division(/) and modulus(%).
Lowest: Addition(+) and substraction(-)
There are different notations are used to represent Arithmetic expressions.
a.infix notation
b.polish/prefix notation
c.postfix/suffix/reverse polish notation.
Infix notation:
In most common arithmetic opeartions,the opeartor is placed b/w the two operands.
1) A+B 2)C-D 3) E*F 4) G/H 5)(a+b)*c
It is called infix notation,it can be parantheised or parantheses free expressions.
Now the infix expression is ended: check out the status of stack if it is not empty pop the entries of satck till it
become empty and write all the poped entries into output. After making stack empty,
The postfix expression of (A+B)*C= AB*C+
NOTE: for more problems refer class notes or lab observation book.
Convert the following infix expression to postfix expression
1. a*(b+c)*d 2.(a+b)*d+e/(f+a*d)+c 3.(a*b)+c/d 4.(((a/b-c)+(d*e))-(a*c))
Recursion:
Recursion is the name given for expressing anything in terms of itself.
A function which contains a call to itself or call to another function ,which eventually causes the first
function to be called,is known as a recursive function.
Recursive procedures generally solve a given problem by reducing the problem to an instance of the
same problem with smaller input.
Once the function is called an activation record is created on the stack
Call to it self is repeated till a base condition is reached.
Once a base condition or terminal condition is reached,the function returns the result to previous copy
of the function.
A sequence of returns ensures that the solution to the original problem obtained.
n!=1.2.3…..(n-2)(n-1)n.
Recursive procedure to find the factorial of N.(algorithm)
FACTORIAL(N,FACT)
1.IF N=0,then:Set Fact:=1 and return
2 call FACTORIAL(N-1,FACT);
3.Set FACT:= N*FACT;
4.return.
Recursive function in C
int fact(int n)
{
If(n==0)
return 1;
return (n*fact(n-1));
}
Note: Write a iterative function(by using loop) to find factorial of n.
2.Fibonacci Sequence:
The fibonacci sequence is series of terms where each suceeding term is a sum of two preceding
terms.
0,1,1,2,3,5,8……
Here,F0=0, F1=1.
F3=F0+F1=0+1=2
Similarly, Fn=Fn-2+Fn-1
Recursive Procedure to find fibanocci sequence.
FIBONACCI(FIB,N)
1)If N=0 or N=1,then :Set FIB:=N, and Return
2)Call FIBONACCI(FIBA,N-2).
3)Call FIBONACCI(FIBB,N-1).
4)Set FIB:=FIBA+FIBB.
5)Return.
int fibonacci(int n)
{
if(n==0)
return 0;
if(n==1)
return 1;
return (fibonacci(n-2)+fibonacci(n-1));
}
Note: Write a iterative function(by using loop) to generate n fibanocci sequence.
3.Ackermann function.
It is a non primitive or nested recursive function.(a primitive recursive is a one which can be
implemented by using loops ex: factorial,GCD etc.)
In computability theory, the Ackermann function, named after Wilhelm Ackermann
Main use of Ackermann function is in mathematical logic
It one of the classical example for recursion.
After Ackermann's publication of his function (which had three nonnegative integer
arguments), many authors modified it to suit various purposes, so that today "the Ackermann
function" may refer to any of numerous variants of the original function. One common version, the
two-argument is defined as follows for nonnegative integers m and n:
Ackermann function in C
int acker(int m,int n)
{
if(m==0)
return n+1;
else if(m>0&&n==0)
return acker(m-1,1);
else return acker(m-1,acker(m,n-1));
}
4.Tower of Hanoi:-
It is a popular game
It is one of the best example how recursion used as tool in developing an algorithm to solve a
particular problem.
Consider 3 pegs A , B & C & suppose on peg A there are placed a finite number n of disks
with decreasing order
Rules
1)Only one disk may be moved at a time
2)At no time can a larger disk be placed on a smaller disk
• For n=3 : AC ,AB ,CB , AC, BA, BC, AC
• For completeness ,we also give the solution to the Towers of Hanoi problem for n=1 & n=2
n=1 : AC (one move)
n=2 : AB , AC , BC (3 moves)
Technique of recursion to develop a general solution
1. Move the top n-1 disks from peg A to peg B
2. Move the top disk from peg A to peg C
3. Move the top n-1 disks from peg B to peg C
QUEUES:
Or capacity-front-1
/*function to implement Dynamic circular queue.*/
void qfull()
{
char *newq,i=0,j=0;
void insert_front()
{
int added_item;
if((front == 0 && rear == MAX-1) || (front == rear+1))
{
printf("Queue Overflow \n");
return;
}
if (front == -1)/*If queue is initially empty*/
{
front = 0;
rear = 0;
}
else
if(front== 0)
front=MAX-1;
else
front=front-1;
printf("Input the element for adding in queue : ");
scanf("%d", &added_item);
deque_arr[front] = added_item ;
}/*End of insert_front()*/
void delete_front()
{
if (front == -1)
{
printf("Queue Underflow\n");
return ;
}
printf("Element deleted from queue is : %d\n",deque_arr[front]);
if(front == rear) /*Queue has only one element */
{
front = -1;
rear = -1;
}
else if(front == MAX-1)
front = 0;
else
front = front+1;
}/*End of delete_front()*/
void delete_rear()
{
if (front == -1)
{
printf("Queue Underflow\n");
return ;
}
printf("Element deleted from queue is : %d\n",deque_arr[rear]);
if(front == rear) /*queue has only one element*/
{
front = -1;
rear=-1;
}
else if(rear == 0)
rear=MAX-1;
else
rear=rear-1;
}/*End of delete_rear() */
void display_queue()
{
int front_pos = front,rear_pos = rear;
if(front == -1)
{
printf("Queue is empty\n");
return;
}
printf("Queue elements :\n");
if( front_pos <= rear_pos )
{
while(front_pos <= rear_pos)
{
printf("%d ",deque_arr[front_pos]);
front_pos++;
}
}
else
{
while(front_pos <= MAX-1)
{
printf("%d ",deque_arr[front_pos]);
front_pos++;
}
front_pos = 0;
while(front_pos <= rear_pos)
{
printf("%d ",deque_arr[front_pos]);
front_pos++;
}
}/*End of else */
printf("\n");
}
void main()
{
int choice;
printf("1.Input restricted dequeue\n");
printf("2.Output restricted dequeue\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1 :input_que();
break;
case 2:output_que();
break;
default:printf("Wrong choice\n");
}/*End of switch*/
}/*End of main()*/
Priority queues:-
• Collection of elements such that each element has been assigned a priority & such that order in which elements
are deleted & processed comes from the following rules
1.An element of higher priority is processed before any element of lower priority
2.Two elements with the same priority are processed according to the order
There are various ways of maintaining a priority queue in memory.out of that two are discused here,
a. One-way List Representation of priority queue.
b. Array representation of priority queue.
a.One-way List Representation of priority queue.
• Each node in the list will contain 3 items of info : an info field INFO , a priority number PNR & a link
number LINK .
• A node X precedes a node Y in the list
(1) When X has higher priority than Y
(2) When both have the same priority but X was added to the list before Y
c. Array Representation of priority queue.
• It uses separate queue for each level of priority.
• Each queue will appear in its own circular array and must have its own pair of pointers i.e
FRONT and REAR.
• Each queue is allocated same amount of space,a two dimensional array can be used instead of
the linear arrays.