Вы находитесь на странице: 1из 55

LAB MANUAL

DATA STRUCTURES USING C


(ALGORITHMS & PROGRAMS)

MANUAL BY:
MS SARIKA ARORA
ASSISTANT PROFESSOR, IT DEPT
KCL-IMT, JALANDHAR

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

DATA STRUCTURES:

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

ALGORITHMS:

So, algorithm is a finite set of instructions or logic, written in order, to accomplish a certain
predefined task. Algorithm is not the complete code or program, it is just the core logic (solution)
of a problem, which can be expressed either as an informal high level description
as pseudocode or using a flowchart.
An algorithm is said to be efficient and fast, if it takes less time to execute and consumes less
memory space. The performance of an algorithm is measured on the basis of following
properties :

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

1. Time Complexity
2. Space Complexity

Space Complexity
Its the amount of memory space required by the algorithm, during the course of its execution.
Space complexity must be taken seriously for multi-user systems and in situations where limited
memory is available.
An algorithm generally requires space for following components:

Instruction Space: Its the space required to store the executable version of the program.
This space is fixed, but varies depending upon the number of lines of code in the program.

Data Space : Its the space required to store all the constants and variables value.

Environment Space : Its the space required to store the environment information needed to
resume the suspended function.

Time Complexity
Time Complexity is a way to represent the amount of time needed by the program to run to
completion.

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

1. ARRAYS:
i)

Matrix Addition
Algorithm
Matadd(a,b,m,n)
1. For i=1to m
2. For j=1 to n
3. C[i][j]=a[i][j]+b[i][j]
4. Exit

Write a program for addition of two matrix.


#include<stdio.h>
#include<conio.h>
void main()
{
int m,n,c,d,first[10][10],second[10][10],sum[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");
for(c=0;c<m;c++)
for(d=0;d<n;d++)
scanf("%d",&first[c][d]);
printf("Enter the elements of second matrix\n");
for(c=0;c<m;c++)
for(d=0;d<n;d++)
scanf("%d",&second[c][d]);
for(c=0;c<m;c++)
for(d=0;d<n;d++)
sum[c][d]=first[c][d] + second[c][d];
printf("Sum of entered matrices:-\n");
for(c=0;c<m;c++)
{ for(d=0;d<n;d++)
printf("%d\t",sum[c][d]);
printf("\n");
}
getch();
}

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

Output

ii)

Traversing of arrays.

Write a program for traversing of array.


#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,k,LB,UB,A[10];
printf("Enter the total number of elements of array:\n");
scanf("%d",&n);
printf("Enter the elements in the array:\n");

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

for(i=1;i<=n;i++)
{
printf("Element number [%d] is ",i);
scanf("%d",&A[i]);
}
LB=1;
UB=n;
k=LB;
printf("\n");
printf("Traversing of array is:\n");
while(k<=UB)
{
printf("Element number [%d] is %d\n",k,A[k]);
k=k+1;
}
getch();
}

Output

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

iii)

Insertion into array.

a) At any position
Write a program to insert element in array.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],i,n,p,el;
clrscr();
printf("Enter the array element\n");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the positon and element\n");
scanf("%d",&p);
printf("Enter element\n");
scanf("%d",&el);
for(i=5;i>(p-1);i--)
{
a[i]=a[i-1];
}
a[i]=el;
printf(After insertion\n);
for(i=0;i<6;i++)
{

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

printf("%d\n",a[i]);
}
getch();
}

Output

b) At end of array.
Write a program to insert element in end of the array.
#include<stdio.h>
#include<conio.h>
void main()
{
int a[50],i,n,p=0,el,j,z;
printf("Enter how many element you want to enter\n");
scanf("%d",&z);
printf("Elemet the array element\n");
for(i=0;i<z;i++)
{
scanf("%d",&a[i]);
p++;
}
printf("Element inserted\n");
if(p>9)
printf("Array is full");
else
{
printf("Enter element for insert in end\n");
scanf("%d",&el);
a[p]=el;

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

p++;
printf("Array after insertion at end\n");
for(i=0;i<p;i++)
printf("%d\n",a[i]);
}
getch();
}
Output

iv)

Deletion from array

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

Write a program to delete element from array.


#include<stdio.h>
#include<conio.h>
void main()
{
int a[5],i,n,j,l,m;
printf("How many value you want to enter\n");
scanf("%d",&m);
printf("Element the array element\n");
for(i=0;i<m;i++)
{
scanf("%d",&a[i]);
}
printf("Element inserted\n");
printf("Which value you want to deleted\n");
scanf("%d",&l);
for(i=l-1;i<m;i++)
{
a[i]=a[i+1];
}
m--;
printf("Element Deleted. Array after value deleted\n");
for(i=0;i<m;i++)
printf("%d\n",a[i]);
getch();
}

Output

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

v)

Searching
a) Linear Search:

Write a program of linear search.


#include <stdio.h>
#include<conio.h>
void main()
{
int array[100],search,c,n,i=0;
printf("Enter the number of elements in array\n");
scanf("%d",&n);
printf("Enter Elements\n", n);
for(c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter the number to search\n");
scanf("%d", &search);
for(c = 0; c < n; c++)
{
if(array[c] == search)
{
printf("%d is present at location %d.\n", search, c+1);
i++;
}
}
if(i==0)
printf("%d is not present in array.\n", search);
Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

getch();
}

Output

b) Binary Search

Write a program of Binary search.


#include <stdio.h>
void main()
{
int c, first=0, last, middle, n, search, array[100];

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

printf("Enter number of elements\n");


scanf("%d",&n);
printf("Enter Elements\n");
for ( c = 0 ; c < n ; c++ )
scanf("%d",&array[c]);
printf("Enter value to find\n");
scanf("%d",&search);
last = n - 1;
middle = (first+last)/2;
while( first <= last && array[middle]!=search)
{
if(search < array[middle] )
last = middle - 1;
else
first = middle + 1;
middle = (first + last)/2;
}
if(array[middle]==search)
printf("%d found at location %d.\n", search, middle+1);
else
printf("Not found! %d is not present in the list.\n", search);
}

Output

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

vi)

Sorting

Sorting is storage of data in sorted order , it can be in ascending or descending order. The term
Sorting comes into picture with the term Searching. There are so many things in our real life that
we need to search, like a particular record in database, roll numbers in merit list, a particular
telephone number, any particular page in a book etc.
Sorting arranges data in a sequence which makes searching easier. Every record which is going
to be sorted will contain one key. Based on the key the record will be sorted.

Sorting Efficiency
There are many techniques for sorting. Implementation of particular sorting technique depends
upon situation. Sorting techniques mainly depends on two parameters. First parameter is the
execution time of program, which means time taken for execution of program. Second is the
space, which means space, taken by the program .

Types of Sorting Techniques


There are many types of Sorting techniques, differentiated by their efficiency and space
requirements. Following are some sorting techniques which we will be covering in next sections.
1. Bubble Sort
2. Insertion Sort
3. Selection Sort

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

a) Bubble Sort

Write a program of Bubble Sort.


#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],n,i,j,tem;
printf("How many element you want enter\n");
scanf("%d",&n);
printf("Enter element of array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=1;i<n;i++)
{
for(j=1;j<n;j++)
{
if(a[j]<a[j-1])
{
tem=a[j];
a[j]=a[j-1];
a[j-1]=tem;
}
}}
printf("Elements after sorting\n");
for(i=0;i<n;i++)
printf("%d \n",a[i]);
getch();
}

Output

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

Complexity Analysis of Bubble Sorting


In Bubble Sort, n-1 comparisons will be done in 1st pass, n-2 in 2nd pass, n-3 in 3rd pass and so
on. So the total number of comparisons will be
(n-1)+(n-2)+(n-3)+.....+3+2+1
Sum = n(n-1)/2
i.e O(n2)
Hence the complexity of Bubble Sort is O(n2).
The main advantage of Bubble Sort is the simplicity of the algorithm .Space complexity for
Bubble Sort is O(1), because only single additional memory space is required for temp variable
Best-case Time Complexity will be O(n), it is when the list is already sorted.

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

b) Insertion Sort
Algorithm:

Write a program of Insertion Sort.


#include<stdio.h>
#include<conio.h>
void main()
{
int data[100],n,temp,i,j;
printf("Enter number of terms: ");
scanf("%d",&n);
printf("Enter elements: \n");
for(i=0;i<n;i++)
scanf("%d",&data[i]);
for(i=1;i<n;i++)
{
temp = data[i];
j=i-1;
while(temp<data[j] && j>=0)
{
data[j+1] = data[j];
--j;
}
data[j+1]=temp;
}

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

printf("In ascending order: \n");


for(i=0; i<n; i++)
printf("%d\n",data[i]);
}

Output

Complexity Analysis of Insertion Sorting


Worst Case Time Complexity : O(n2)
Best Case Time Complexity : O(n)
Average Time Complexity : O(n2)
Space Complexity : O(1)

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

c) Selection Sort

Write a program of Selection Sort.


#include<stdio.h>
void main()
{
int a[20],i,j,temp,loc,n;
printf("Enter how many element you want to enter\n");
scanf("%d",&n);
printf("Enter elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(j=1;j<n;j++)
{
loc=j-1;
for(i=j;i<n;i++)
{
if(a[loc]>a[i])
{
loc=i;
}
}
if((a[j-1]<a[loc])||(j-1)==loc)
continue;
temp=a[j-1];
a[j-1]=a[loc];
a[loc]=temp;
}
printf("Elements after sorting\n");
for(i=0;i<n;i++)

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

printf("%d,",a[i]);
}

Output

Complexity Analysis of Selection Sorting


Worst Case Time Complexity : O(n2)
Best Case Time Complexity : O(n2)
Average Time Complexity : O(n2)
Space Complexity : O(1)

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

2. STACKS
Stack is an abstract data type with a bounded (predefined) capacity. It is a simple data structure
that allows adding and removing elements in a particular order. Every time an element is added,
it goes on the top of the stack, the only element that can be removed is the element that was at
the top of the stack, just like a pile of objects.

Basic features of Stack


1. Stack is an ordered list of similar data type.
2. Stack is a LIFO structure. (Last in First out).
3. push() function is used to insert new elements into the Stack and pop() is used to delete an
element from the stack. Both insertion and deletion are allowed at only one end of Stack
called Top.
4. Stack is said to be in Overflow state when it is completely full and is said to be
in Underflow state if it is completely empty.

Applications of Stack
The simplest application of a stack is to reverse a word. You push a given word to stack - letter
by letter - and then pop letters from the stack.
There are other uses also like : Parsing, Expression Conversion(Infix to Postfix, Postfix to
Prefix etc) and many more.
Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

i)

Recursion.
a) Factorial of a number

Write a progam of factorial using recursion.


#include<stdio.h>
int fact(int);
void main()
{
int n,f;
printf("Enter number for calculate factorial: ");
scanf("%d",&n);
f=fact(n);
printf("Factorial of %d is %d.",n,f);
}
int fact(int a)
{
if(a==0)
return 1;
else
return a*fact(a-1);
}

Output

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

b) WAP to call function main() recursively.


# include <stdio.h>
# include <conio.h>
main ()
{
int main (void);
printf ("\n Hello");
return (main ());
}

OUTPUT:

Hello
Hello
Hello
Hello
Hello
Hello

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

ii)

Stack operations: PUSH,POP

Write a progam to implement push and pop operation on stack.


#include <stdio.h>
#include<conio.h>
#define MAX 10
int top, status;
void display (int stack[])
{ int i;
printf ("\nThe Stack is: \n--");
{
for (i=top; i>=0; --i)
printf ("--\n%d\n--",stack[i]);
}
printf("--\n");
}
void main()
{

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

int stack [MAX]={10,20}, item, t;


int ch;
top = 1;
do
{ do
{
printf ("1.PUSH (Insert) in the Stack");
printf ("\n2.POP (Delete) from the Stack");
printf ("\n3.Exit (End the Execution)");
printf ("\nEnter Your Choice: ");
scanf ("%d", &ch);
if (ch<1 || ch>3)
printf ("\nInvalid Choice, Please try again");
}while (ch<1 || ch>3);
if(ch==1)
{
printf ("Enter the Element to be pushed : ");
scanf ("%d", &item);
if (top==4)
printf ("\nStack is Full");
else
{
top++;
stack[top]=item;
printf ("Element Inserted");
display(stack);
}
}
else if(ch==2)
{
if (top==0)
printf ("\nStack is Empty\n");
else
{
t=stack[item];
top--;
printf("Element Removed");
display(stack);
}
}
else
printf ("\nEND OF EXECUTION");
Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

}while (ch != 3);


getch();
}

Output

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

iii)

Infix to Postfix Expressions

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

Write a program to convert an expression from infox to postfix.


#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#define MAX 100
typedef struct stack
{
int data[MAX];
int top;
}stack;
int priority(char);
void init(stack *);
int empty(stack *);
int full(stack *);
char pop(stack *);
void push(stack *,char);
char top(stack *);
void main()
{
stack s;
char x;
int token;
init(&s);
clrscr();
printf("Enter infix expression:\n");
while((token=getchar())!='\n')
{
if(isalnum(token))
printf("%c",token);
else
if(token == '(')
push(&s,'(');
else
{
if(token == ')')
while((x=pop(&s))!='(')
printf("%c",x);
else
{
while(priority(token) <= priority(top(&s)) && !empty(&s))

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

{
x=pop(&s);
printf("%c",x);
}
push(&s,token);
}
}
}
while(!empty(&s))
{
x=pop(&s);
printf("%c",x);
}
getch();
}
int priority(char x)
{
if(x == '(')
return(0);
if(x == '+' || x == '-')
return(1);
if(x == '*' || x == '/' || x == '%')
return(2);
return(3);
}
void init(stack *s)
{
s->top=-1;
}
int empty(stack *s)
{
if(s->top==-1)
return(1);
else
return(0);
}
int full(stack *s)
{
if(s->top==MAX-1)
return(1);
else
return(0);
}
Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

void push(stack *s,char x)


{
s->top=s->top+1;
s->data[s->top]=x;
}
char pop(stack *s)
{
int x;
x=s->data[s->top];
s->top=s->top-1;
return(x);
}
char top(stack * s)
{
return(s->data[s->top]);
}

Output

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

iv)

WAP to perform following stack operations


*Create a stack with item code and quantity
ITEM

QUANTITY

001

450

002

003

487

004

101

005

500

006

007

359

**Delete the items having quantity zero and update the stack.
#include<stdio.h>
#include<conio.h>
void main()
{
int top,a[]={001,002,003,004,005,006,007};
int top1,b[]={450,0,487,101,500,0,359};
clrscr();
printf("\n \t ITEMS IN STACK ARE:");
for(top=0;top<7;top++)
{
printf("\n \t \t %d ",a[top]);
printf("\t \t %d ",b[top]);
} printf("\n \n \t AFTER DELETION ITEMS IN STACK
ARE:");
for(top=0;top<7;top++)
{
if(b[top]==0)
{
top1=top;
while(top1<7)
{
a[top1]=a[top1+1];
b[top1]=b[top1+1];
top1++;
}
Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

}
{

}
for(top=0;top<5;top++)
printf("\n\t \t %d ",a[top]);
printf("\t \t %d ",b[top]);

}
getch();
}

OUTPUT:

Analysis of Stacks
Below mentioned are the time complexities for various operations that can be performed on the Stack data
structure.

Push Operation : O(1)

Pop Operation : O(1)

Top Operation : O(1)

Search Operation : O(n)

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

3. Queues
Queue is also an abstract data type or a linear data structure, in which the first element is
inserted from one end called REAR(also called tail), and the deletion of exisiting element
takes place from the other end called as FRONT(also called head). This makes queue as
FIFO data structure, which means that element inserted first will also be removed first.
The process to add an element into queue is called Enqueue and the process of removal
of an element from queue is called Dequeue.

Applications of Queue
Queue, as the name suggests is used whenever we need to have any group of objects in an order
in which the first one coming in, also gets out first while the others wait for there turn, like in the
following scenarios :
1. Serving requests on a single shared resource, like a printer, CPU task scheduling etc.
2. In real life, Call Center phone systems will use Queues, to hold people calling them in an
order, until a service representative is free.
3. Handling of interrupts in real-time systems. The interrupts are handled in the same order as
they arrive, First come first served.

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

i)

Queue insertion and deletion:


Algorithm:

Write a Program to perform different operation with Queue such as


insert,delete and display elements.
#include<conio.h>
#include<stdio.h>
#define MAX 10
struct que
{
int x[10];
int f,r;
}q;
void main()
{
int choice,i,n;
q.f=1;
q.r=0;
printf("\n\n1-Insert\n2-Delete\n3-Display\n4-Exit\n");
do

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

{
printf("Select option\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
if(q.r>MAX-1)
{
printf("\nQueue overflow");
break;
}
else
{
printf("Enter Element\n");
scanf("%d",&n);
q.x[++q.r]=n;
printf("Element Inserted\n");
break;
}
case 2:
if(q.f>q.r)
printf("Queue is empty\n");
else
{
printf("\n\nYou are deleting %d",q.x[q.f]);
q.f++;
}
break;
case 3:
printf("\nQueue\n");
printf("||\t");
for(i=q.f;i<=q.r;i++)
printf("%d\t",q.x[i]);
printf("||");
break;
case 4:
break;
}
}while(choice!=4);
}
Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

Output

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

ii)

Circular Queue insertion and deletion


Algorithm:

Write a Program to perform different operation with Circular Queue such as


insert,delete and display elements.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define max 5
int q[10],front=0,rear=-1;
void main()
{ int ch;

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

void insert();
void delet();
void display();
printf("Circular Queue operations\n");
printf("1.insert\n2.delete\n3.display\n4.exit\n");
while(1)
{
printf("Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: insert();
break;
case 2: delet();
break;
case 3:display();
break;
case 4:exit(0);
default:printf("Invalid option\n");
} } }
void insert()
{
int x;
if((front==0&&rear==max-1)||(front>0&&rear==front-1))
printf("Queue is overflow\n");
else
{
printf("Enter element to be insert:");
scanf("%d",&x);
if(rear==max-1&&front>0)
{
rear=0;
q[rear]=x;
}
else
{
if((front==0&&rear==-1)||(rear!=front-1))
q[++rear]=x;
} } }
void delet()
{
int a;
if((front==0)&&(rear==-1))
{
printf("Queue is underflow\n");
getch();

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

exit(0);
}
if(front==rear)
{
a=q[front];
rear=-1;
front=0;
}
else
if(front==max-1)
{
a=q[front];
front=0;
}
else a=q[front++];
printf("Deleted element is:%d\n",a);
}
void display()
{
int i,j;
if(front==0&&rear==-1)
{
printf("Queue is underflow\n");
getch();
exit(0);
}
if(front>rear)
{
for(i=0;i<=rear;i++)
printf("\t%d",q[i]);
for(j=front;j<=max-1;j++)
printf("\t%d",q[j]);
printf("\nrear is at %d\n",q[rear]);
printf("\nfront is at %d\n",q[front]);
}
else
{
for(i=front;i<=rear;i++)
{
printf("\t%d",q[i]);
}
printf("\nrear is at %d\n",q[rear]);
printf("\nfront is at %d\n",q[front]);
}
printf("\n");
}

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

getch();
}

Output

iii)

WAP to insert and display the eight alphabetic characters in a


queue.

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct list
{
char data;
struct list *next;
};
typedef struct list node;

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

void qinsert(node**,node**);
void disp(node*);
void main()
{
int opt;
char ch;
node *front;
node *rear;
clrscr();
rear=front=NULL; //initially front and rear are assigned NULL
do
{ printf("\nEnter your option to perform Queue operation:::\n");
printf("1. Insert\n");
printf("2. Display the Queue\n");
scanf("%d",&opt);
switch(opt)
{
case 1: qinsert(&front,&rear);
break;
case 2: disp(front);
break;
}
printf("\nDo you wish to continue[y/n]:");
ch=(char)getche();
}while(ch=='Y' || ch=='y');
printf("\nPress any key to exit from the program");
getch();
}
void qinsert(node **front,node **rear)
{
node *new_element; /* New element to be inserted */
new_element=(node*)malloc(sizeof(node)); //memory allocated
new_element->next=NULL;
printf("\nEnter the character to be inserted in the queue:");
fflush(stdin);
scanf("%c",&(new_element->data));
if(*front==NULL && *rear==NULL)
{
*front=new_element;
*rear=new_element;
}
else
{
(*rear)->next=new_element;
*rear=new_element;
}

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

}
void disp(node *f) //Displaying the queue
{
printf("\nElements in the Queue are:");
while(f!=NULL)
{
printf(" %c ",f->data);
f=f->next;
}
}

OUTPUT:

Analysis of Queue

Enqueue : O(1)

Dequeue : O(1)

Size : O(1)

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

4. LINKED LIST
Introduction to Linked Lists
Linked List is a linear data structure and it is very common data structure which consists of
group of nodes in a sequence which is divided in two parts. Each node consists of its own data
and the address of the next node and forms a chain. Linked Lists are used to create trees and
graphs.

Advantages of Linked Lists

They are a dynamic in nature which allocates the memory when required.

Insertion and deletion operations can be easily implemented.

Stacks and queues can be easily executed.

Linked List reduces the access time.

Disadvantages of Linked Lists

The memory is wasted as pointers require extra memory for storage.

No element can be accessed randomly; it has to access each node sequentially.

Reverse Traversing is difficult in linked list.

Applications of Linked Lists

Linked lists are used to implement stacks, queues, graphs, etc.

Linked lists let you insert elements at the beginning and end of the list.

In Linked Lists we dont need to know the size in advance.

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

Types of Linked Lists

Singly Linked List : Singly linked lists contain nodes which have a data part as well as an
address part i.e. next, which points to the next node in sequence of nodes. The operations we
can perform on singly linked lists are insertion, deletion and traversal.

Doubly Linked List : In a doubly linked list, each node contains two links the first link
points to the previous node and the next link points to the next node in the sequence.

Circular Linked List : In the circular linked list the last node of the list contains the address
of the first node and forms a circular chain.

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

i)
POINTERS:
Write a program using pointer.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,*c,*d;
printf("Enter value of a and b\n");
scanf("%d%d",&a,&b);
c=&a;
d=&b;
*c=*c+*d;
printf("Sum is %d",*c);
getch();
}

Output

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

ii)
Single linked list:
a) Insertion Operation
Algorithm:

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

Write a program to implement insertion operation in single linked list.


#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
{
int data;
struct node *next;
}*start=NULL;
void creat()
{
char ch;
do
{
struct node *new_node,*current;
new_node=(struct node *)malloc(sizeof(struct node));
printf(\nEnter the data : );
scanf(%d,&new_node->data);
new_node->next=NULL;
if(start==NULL)
{
start=new_node;
current=new_node;
}
else
{
current->next=new_node;
current=new_node;
}
printf(\nDo you want to create another : );
ch=getche();
}while(ch!=n);
}
void display()
{
struct node *new_node;
printf(\nThe Linked List : n);
new_node=start;
while(new_node!=NULL)
{
printf(%d-,new_node->data);
new_node=new_node->next;
}

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

printf(NULL);
}
void main()
{
creat();
display();
}

Output

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

b) Deletion Operation:

Write a program to implement deletion operation in single linked list.


#include<stdio.h>
#include<conio.h>
//Create a basic structure for NODE from which new nodes can be created.
struct node
{
int data;
struct node *link;
};
//Initialize pointers as globals so that they do not need to be passed in functions.
struct node *header, *ptr, *ptr1, *temp;
void insert_end();

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

void delete_front();
void delete_end();
void delete_any();
void display();
void main()
{
int choice;
int cont = 1;
//Allocate memory for header node.
header = (struct node *) malloc(sizeof(struct node));
clrscr();
//Set the content of header node
header->data = NULL;
header->link = NULL;
while(cont == 1)
{
//Display menu to the user
printf("\n1. Insert at end\n");
printf("\n2. Delete from front\n");
printf("\n3. Delete from end\n");
printf("\n4. Delete from anywhere\n");
printf("\n5. Display linked list\n");
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
insert_end();
break;
case 2:
delete_front();
break;
case 3:
delete_end();
break;
case 4:
delete_any();
break;
case 5:
display();
break;

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

}
printf("\n\nDo you want to continue? (1 / 0): ");
scanf("%d", &cont);
}
getch();
}
//Function to insert a node at the end of a single linked list.
void insert_end()
{
int data_value;
printf("\nEnter data of the node: ");
scanf("%d", &data_value);
temp = (struct node *) malloc(sizeof(struct node));
//Traverse to the end of the linked list.
ptr = header;
while(ptr->link != NULL)
{
ptr = ptr->link;
}
temp->data = data_value;
temp->link = ptr->link;
ptr->link = temp;
}
//Function to delete a node from the front of a linked list.
void delete_front()
{
//If the list is already empty
if(header->link == NULL)
{
printf("\nEmpty Linked List. Deletion not possible.\n");
}
else
{
ptr = header->link;
header->link= ptr->link;
free(ptr);
printf("\nNode deleted from the front.\n");
}

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

}
//Function to delete a node from the end of a linked list.
void delete_end()
{
if(header->link == NULL)
{
printf("\nEmpty Linked List. Deletion not possible.\n");
}
else
{
//Traverse to the end of the list.
ptr = header;
while(ptr->link != NULL)
{
ptr1 = ptr;
ptr = ptr->link;
}
ptr1->link = ptr->link;
free(ptr);
printf("\nNode deleted from the end.\n");
}
}
//Function to delete any node from linked list.
void delete_any()
{
int key;
if(header->link == NULL)
{
printf("\nEmpty Linked List. Deletion not possible.\n");
}
else
{
printf("\nEnter the data of the node to be deleted: ");
scanf("%d", &key);
ptr = header;
while((ptr->link != NULL) && (ptr->data != key))
{
ptr1 = ptr;
ptr = ptr->link;
}
if(ptr->data == key)
{

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

ptr1->link = ptr->link;
free(ptr);
printf("\nNode with data %d deleted.\n", key);
}
else
{
printf("\nValue %d not found. Deletion not possible.\n", key);
}
}
}
//Function to display the contents of the linked list.
void display()
{
printf("\nContents of the linked list are: \n");
//Print the contents of the linked list starting from header
ptr = header;
while(ptr->link != NULL)
{
ptr = ptr->link;
printf("%d ", ptr->data);
}
}
OUTPUT:

Data Structures using C

Ms. Sarika Arora,IT Dept,KCL-IMT,Jalandhar

Вам также может понравиться