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

Ds Module 2 Notes22

Uploaded by

VIJAY C P IS&E
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Ds Module 2 Notes22

Uploaded by

VIJAY C P IS&E
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

What is stack?

 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” is the term used to insert an element into stack.


b. ”pop” is the term used to delete an element from stack.

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

STACK TOP MAXSTK-1

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

Note: C program to perform stack operations.


Refer lab program-3

ADT stack is(Abstract Data type)


Objects: a finite ordered list with zero or more elements
Functions:
Stack create(max)::= Create an empty satck,whose maximum size=max
Boolean ISFull(stack)::= return true if top=max-1 else return false.
Stack push(item)::=push element ,item to stack
Element pop()::= if(top=-1) stack is empty,else return topmost element

Stack using Dynamic Arrays

 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)

The implementation of Stack by using dynamic arrays is as follows


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int *stack;
int capacity=1;
int top=-1,item;
void push()
{
if(top==capacity-1)
{
stackfull();//which double the memory when stack is full
}
printf("enter an item to insert \n");
scanf("%d",&item);
stack[++top]=item ;
}
void pop()
{
if(top==-1)
{
printf("underflow\n");
return;
}
item=stack[top--];
printf("item deleted is %d \n",item);
}
void stackfull()
{

stack=realloc(stack,capacity*2*sizeof(int));// doubling the memory


if(stack==NULL)// IF MEMORY IS IN SUFFICIENT
{
printf(“memory is insuffient\n”);
exit(0);
}
capacity=capacity*2; // doubling the stack size

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.

Polish /Prefix notation:


It is named after the polish mathematician Jan Lukasiewicz,refers to the notation in which the
operator symbol is placed before its two operations.

Example: +AB, -CD, *+ABC

Convert infix in to Polish(prefix):

1. (a+b)*c= [+ab]*c= *+abc . where [ ] indicates partial translation.


2. A+(B*C)=A+[*BC]=+A*BC
3. (A+B)/(C-D)=?

Postfix/Suffix/Reverse polish notation:


In which operator is placed after the operands.
AB+ CD* AB+C* ABC*+
 Computer usually evaluates an arithmetic expression written in infix notation in two steps
i)it converts the expression into potfix notation
ii)then it evaluate that expression.
 stack is the main tool used to acomplish this task.

Converting infix expression into postfix/suffix/reverse polish expression


Procedure to convert by using satck
 read one input symbol at a time from the array of characters(infix expression)
 if a input symbol is an operand .write it into output(postfix)
 if a input synmbol is an operator,push it in to stack,if the stack is empty.if stack is not empty
compare the precedance of stack symbol and input symbol. pop all the stack symbol having
higher or equal prority(write poped entries into stack) and then only push operator in to stack.
 If the input symbol is left parentheses ‘(‘ push it into satck.
 If input symbol is right parentheses ‘)”,pop entries of satck and write those entries into output till
you find “(‘ in satck. (don’t write ‘(‘ into output).
 When you finish reading the string,pop all the left out synbols from the stack and store in output.

Ex: convert (A*B)+C into postfix using stack.


Input Stack Top Output[postfix]
symbol 0 1 2 3
( ( 0
A ( 0 A
* ( * 1 A
B ( * 1 AB
) -1 AB*
+ + 0 AB*
C + 0 AB*C

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))

NOTE: C program to convert infix to postfix:(refer lab program-4)

EVALUATION OF POSTFIX EXPRESSION:


Procedure to evaluate :-
1.read only one input symbol at a time from postfix expression.
2.if input symbol is operand ,push operand in to stack(before pushing convert that into integer).
3.if input symbol is opeartor ,pop two operands from stack perform operation and push result into satck.
4.repeat the process till the expression become empty.
5.finally result will be stored in the top of the stack(top==0).

Evaluate the postfix expression :- 62/3-42*+


Stack TOP=-1 Process
Input
0 1 2 3 4 5 (intially)
6 6 0 push 6 into stack

2 6 2 1 Push 2 into stack


/ 3 0 Pop 6 ,2 and divide ,push result into stack
3 3 3 1 push 3 into stack
- 0 0 Pop 3 ,3 and substract,push result into stack
4 0 4 1 Push 4 into stack
2 0 4 2 2 Push 2 into satck
Pop 2 and 4 apply opeartor and push result
* 0 8 1
int stack
Pop 8 and 0 from the stack apply opeartor
+ 8 0
and push result into stack.
Result=8
Examples:
NOTE: C program to evaluate suffix/postfix expression:(refer lab-program-5a)

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.

The recursive procedure(function) must have the following properties.


 There must be certain condition ,called base condition,for which the procedure(function) does not call
itself.
 Each time the procedure(function) does call itself (directly or indirectly),it must be closer to the base
condition.

Examples for recursive function.


1. Factorial function
The product of the positive integers from 1 to n,inclusive,is called “n factorial” and is usually
denoted by n!.

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.

Recursive function in C to generate fibonacci sequence.

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. A(m,n)


1)A(m,n)=n+1, when m=0
2)A(m,n)=A(m-1,1), when m>0, n=0
3) A(m,n)=A(m-1, A(m,n-1)) when m>0 and n>0

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));
}

What is the value of A(1,3)?

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 : AC ,AB ,CB , AC, BA, BC, AC
• For completeness ,we also give the solution to the Towers of Hanoi problem for n=1 & n=2
n=1 : AC (one move)
n=2 : AB , AC , BC (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

Recursive procedure to Tower of Hanoi:- TOWER(N,BEG,AUX,END)


1. When n=1,then
a. TOWER(1, BEG,AUX,END) or Write:= BEGEND
b. return
2. When n>1

a. TOWER(N-1,BEG,END,AUX) [ Move the top n-1 disks from peg A to peg B]


b. TOWER(1, BEG,AUX,END) or Write:- BEGEND

c. TOWER(N-1,AUX,BEG,END) [Move the top n-1 disks from peg B to peg C ]


C program to Tower of Hanoi
#include<stdio.h>
#include<conio.h>
int tower(int n,char beg,char aux,char end)
{
if(n==1)
{
printf("thed disk 1 is move from %c to %c\n",beg,end);
return;
}
tower(n-1,beg,end,aux);
printf("the disk %d is moved from %c to %c\n",n,beg,end);
tower(n-1,aux,beg,end);
}
void main()
{
int num;
printf("enter the number of disk \n");
scanf("%d",&num);
tower(num,'A','B','C');
getch();
}

GCD recursive function:[


int gcd(int n1, int n2)
{
if (n2!=0)
return gcd(n2, n1%n2);
else
return n1;
}

QUEUES:
Or capacity-front-1
/*function to implement Dynamic circular queue.*/

void qfull()
{
char *newq,i=0,j=0;

newq=malloc(2*capacity*sizeof(*newq)); // create a newq by doubling the memory

printf("queue is about to full double the queue size\n");


while(front!=capacity-1)//copying second segment of queue from queue[front+1] to capacity-1
{
newq[i++]=queue[++front];
}
while(i!=capacity-1) //copying first segment of queue from queue[0] to rear
{
newq[i++]=queue[j++];
}
front=2*capacity-1; //new value of front in newq
rear=capacity-2; // new value of rear in newq
capacity=capacity*2; // doubling maximum size
free(queue);
queue=newq; //making newq as queue
}

Double Ended queue(deques):-


A deque is a linear list in which elements can be added or removed at either end but not in the middle.
Deque is maintained by a circular array DEQUE with pointers front and rear.

There are two variations of Deque are,


1.input restricted deque.
2.output restricted deque.
1.input restricted deque:-
Which allows the insertion from only one end of the list but allows deletions at both ends of the list.
2.output-restricted deque.
Which allows the deletion from only one end of the list but allows insertion at both ends of the list.

Note: insert front:- from right to left - max-1 to 0


Delete fron:- from left to right- 0 to max-1
Insert rear:- from left to right - 0 to max-1
Delete rear:- from right to left - max-1 to 0.
/* Program of input and output restricted dequeue using array*/
#include<stdio.h>
#define MAX 5
int deque_arr[MAX];
int front = -1;
int rear = -1;
void input_que()
{
int choice;
while(1)
{
printf("1.Insert at rear\n");
printf("2.Delete from front\n");
printf("3.Delete from rear\n");
printf("4.Display\n");
printf("5.Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:insert_rear();
break;
case 2:delete_front();
break;
case 3:delete_rear();
break;
case 4:display_queue();
break;
case 5:exit();
default:printf("Wrong choice\n");
}/*End of switch*/
}/*End of while*/
}/*End of input_que() */
void output_que()
{
int choice;
while(1)
{
printf("1.Insert at rear\n");
printf("2.Insert at front\n");
printf("3.Delete from front\n");
printf("4.Display\n");
printf("5.Quit\n");
printf("Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:insert_rear();
break;
case 2:insert_front();
break;
case 3:delete_front();
break;
case 4:display_queue();
break;
case 5:exit();
default:printf("Wrong choice\n");
}/*End of switch*/
}/*End of while*/
}/*End of output_que() */
void insert_rear()
{
int added_item;
if((front == 0 && rear == MAX-1) || (front == rear+1))
{
printf("Queue Overflow\n");
exit(0);
}
if (front == -1) /* if queue is initially empty */
{
front = 0;
rear = 0;
}
else if(rear == MAX-1) /*rear is at last position of queue */
rear = 0;
else
rear = rear+1;
printf("Input the element for adding in queue : ");
scanf("%d", &added_item);
deque_arr[rear] = added_item ;
}/*End of insert_rear()*/

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.

You might also like