Unit 1
Unit 1
1.Primitive Data Structures : Primitive data structures are the basic data structures and are directly operated
upon by the machine instructions are known as Primitive Data Structures. They are
1.Integer
2.Float
3.Char
4.Double
5.Boolean
2: Non-Primitive Data Structures : The Data structures that are not directly processed by machine using its
instructions are known as Non-Primitive Data Structures.
Non-Primitive Data Structures are
1. Linear Data Structure
2. Non - Linear Data Structure
Linear Data Structures
If a data structure organizes the data in sequential order, then that data structure is
called a Linear Data Structure.
Example
1. Arrays
2. List (Linked List)
3. Stack
4. Queue
Non - Linear Data Structures
If a data structure organizes the data in random order, then that data structure is
called as Non-Linear Data Structure.
Example
1. Tree
2. Graph
3. Dictionaries
4. Heaps
5. Tries, Etc.,
DATA STRUCTURES OPERATIONS:
The following data structure operations play a major role in processing of data.
1. Creating : This is the first operation to create a data structure. This is just declaration and initialization
of the data structure and reserved memory locations for data element.
2. Inserting : Adding new element to the structure.
3. Deleting : Removing a element from the structure.
4. Traversing:Visiting each element of the data structure at least once.
5. Searching : Finding the location of the record with a given key value, or finding the locations of
all records, which satisfy one or more conditions in the data.
6. Sorting:Arranging the data elements in some logical order, i.e., in ascending and descending
order.
7. Merging : Combine the data elements in two different sorted sets into a single sorted set.
• The abstract datatype is special kind of datatype, whose behavior is defined by a set of values and set of
operations.
• The keyword “Abstract” is used as we can use these datatypes, we can perform different operations.
• But how those operations are working that is totally hidden from the user.
• The ADT is made of with primitive datatypes, but operation logics are hidden.
There are three types of ADTs:
1.Stack
2.Queue
3.List
LINKED LIST
• The linked list is a linear data structure that contains a sequence of elements such that each element
links to its next element in the sequence.
• Linked list is a dynamic data structure whose length can be increased or decreased at run time.
• A linked list is used to store a collection of elements. Each element is stored in a linked list is called
"Node".
data next
10 pointer
Node
• Each “Node" contains two fields: Data field and Next field.
• Data field is used to store actual value of the node
• Next field is used to store the address of next node in the list.
struct node
{
int data;
struct node *next;
};
1. Creation
2. Insertion
3. Deletion
4. Display (or) Traversing
5. Searching
Before we implement actual operations, first we need to set up an empty list. First, perform the following steps
before implementing actual operations.
• Step 1 - Include all the header files which are used in the program.
• Step 2 - Declare all the user defined functions.
• Step 3 - Define a Node structure with two members data and next
• Step 4 - Define a Node pointer 'head' and set it to NULL.
• Step 5 - Implement the main method by displaying operations menu and make suitable function calls in
the main method to perform user selected operation.
1.Creation:
Step 1: Create a newNode with given value, Say "ptr".
Step 2: Check whether list is Empty (head == NULL).
Step 3: If it is Empty then, set head = ptr and define a Node pointer 'temp' and initialize with 'head'.
Step 4: If it is Not Empty then, set temp->next=ptr, temp= temp->next .
Example:
Step 1:Create a newnode named "ptr" and store the values(ptr->data=num,ptr->next=NULL)
data next
10 NULL
ptr 1000
Step 2:If head=NULL,make newnod as head and head as temp(head=ptr and temp=head)
data next
10 NULL
head temp 1000
Program:
void create()
{
struct node *ptr;
int i,n,val;
printf("Enter Number of Elements\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
ptr=(struct node*)malloc(sizeof(struct node));
printf("Enter the data of node %d: ", i);
scanf("%d",&val);
ptr->data=val;
ptr->next=NULL;
if(head==NULL)
{
head=ptr;
temp=head;
}
else
{
temp->next=ptr;
temp=temp->next;
}
}
}
2.Insertion :
In a single linked list, the insertion operation can be performed in three ways. They are as follows...
1. Inserting At Beginning of the list
2. Inserting At End of the list
3. Inserting At Specific location in the list
Inserting At Beginning of the list :
Step 1 - Create a newNode with givenvalue, Say “ptr “.
Step 2 - Check whether list is Empty (head == NULL)
Step 3 - If it is Empty then, set ptr→next = NULL and head = ptr.
Step 4 - If it is Not Empty then, set ptr→next = head and head = ptr.
Example:
Existing list with 20,30 and 40 values
data next data next data next
20 3000 30 4000 40 NULL
head 2000 3000 4000
Program:
void insert_beg()
{
int num;
ptr=(struct node*)malloc(sizeof(struct node));
printf("Enter data:");
scanf("%d",&num);
ptr->data=num;
ptr->next=NULL;
if(head==NULL)
{
head=ptr;
}
else
{
ptr->next=head;
head=ptr;
}
Inserting At End of the list
Step 1 - Create a newNode with given value ,Say “ ptr “ and ptr→ next as NULL.
Step 2 - Check whether list is Empty (head == NULL).
Step 3 - If it is Empty then, set head = ptr.
Step 4 - If it is Not Empty then, define a node pointer temp and initialize with head.
Step 5 - Keep moving the temp to its next node until it reaches to the last node in the list . (until temp → next
is equal to NULL).
Step 6 - Set temp → next = ptr.
Example:
Step 2:Make head as temp(temp=head) and traverse to the last node of the list(temp=temp->next)
data next data next data next data next
10 2000 20 3000 30 NULL 40 NULL
head 1000 2000 temp 3000 ptr 4000
Program:
void insert_end()
{
int num;
ptr=(struct node*)malloc(sizeof(struct node));
printf("Enter data:");
scanf("%d",&num);
ptr->data=num;
ptr->next=NULL;
if(head==NULL)
{
head=ptr;
}
else
{
temp=head;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=ptr;
}
}
Step 4 - If it is Not Empty then, define a node pointer temp and initialize with head.
( temp=head )
Step 5 - Keep moving the temp to its next node until it reaches to the node after which we want to insert the
newNode
Step 6 - Finally, Set 'ptr → next = temp→ next' and 'temp → next = ptr'
Example:
Program:
int insert_pos()
{
int pos,i=1,num;
if(head==NULL)
{
printf("List is empty!!");
return 0;
}
ptr=(struct node*)malloc(sizeof(struct node));
printf("Enter data:");
scanf("%d",&num);
printf("Enter position to insert:");
scanf("%d",&pos);
ptr->data=num;
ptr->next=NULL;
temp=head;
while(i<pos)
{
temp=temp->next;
i++;
}
ptr->next=temp->next;
temp->next=ptr;
return 0;
}
2.Deletion
In a single linked list, the deletion operation can be performed in three ways. They are as follows...
1. Deleting from Beginning of the list
2. Deleting from End of the list
3. Deleting a Specific Node
Deleting from Beginning of the list
Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate the function.
Step 3 - If it is Not Empty then, define a Node pointer 'temp' and initialize with head. Step 4 - Check whether
list is having only one node (temp → next == NULL)
Step 5 - If it is TRUE then set head = NULL and delete temp (Setting Empty list conditions) Step 6 - If it is
FALSE then set head = temp → next, and delete temp.
Step 6 - If it is FALSE then set head = temp → next, and delete temp.
Example:
Program:
void delete_beg()
{
if(head==NULL)
{
printf("List is empty cant delete\n");
}
else
{
temp=head;
if(head->next == NULL)
{
head = NULL;
printf("Deleted element is %d",temp->data);
free(temp);
}
else
{
head=head->next;
printf("Deleted element is %d",temp->data);
free(temp);
}
}
}
Deleting from End of the list
Step 1. Check whether list is Empty (head == NULL)
Step 2 . If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate the function.
Step 3. If it is Not Empty then, define two Node pointers 'temp' and 'temp1' and initialize 'temp' with head.
Step 4. Check whether list has only one Node (temp → next == NULL)
Step 5. If it is TRUE. Then, set head = NULL and delete temp. And terminate the function.
Step 6. If it is FALSE. Then, set 'temp1 = temp ' and move temp to its next node. Repeat the same until it
reaches to the last node in the list. (until temp → next == NULL)
Step 7. Finally, Set temp1 → next = NULL and delete temp.
Example:
Deleting at Ending
Program:
void delete_end()
{
if(head==NULL)
{
printf("Empty List cant delete\n");
}
else
{
temp=head;
if(head->next == NULL)
{
head = NULL;
printf("Deleted element is %d",temp->data);
free(temp);
}
else
{
while(temp->next!=NULL)
{
temp1=temp;
temp=temp->next;
}
temp1->next=NULL;
last=temp1;
printf("Deleted element is %d",temp->data);
free(temp);
}
}
}
Program:
int delete_pos()
{
int pos,i=1;
if(head==NULL)
{
printf("List is empty!!");
return 0;
}
printf("Enter position to delete:");
scanf("%d",&pos);
temp=head;
while(i<pos-1)
{
temp=temp->next;
i++;
}
temp1=temp->next;
temp->next=temp1->next;
temp1->next=NULL;
printf("Deleted element is %d",temp1->data);
free(temp1);
return 0;
}
Program:
void display()
{
printf("The Elements are \n");
temp=head;
while(temp!=NULL)
{
printf("%d->",temp->data);
temp=temp->next;
}
printf("NULL");
}
5.Searching :
Step 1-Initialize a node pointer, temp=head.
Step 2-Input element to search from user. Store it in some variable say "key".
Step 3-Declare a variable to store index of found element through list, say "count=0".
Step 4-Do following while temp is not NULL
temp->data == key , if the condition is true, The element is found.
Step 5-otherwise ,increment count ( count++) and move temp to its next node (temp = temp->next )
Step 6-while temp is NULL, The element is not found.
Program:
int searchnode()
{
struct node *temp = head;
int key,count=0;
printf("\nEnter the element to be searched in the list : ");
scanf("%d",&key);
while(temp != NULL)
{
if(temp->data == key)
{
printf("\nElement %d found at position %d",key,count);
return 0;
}
else
{
count+=1;
temp = temp->next;
}
}
printf("\n Element %d is not found in the list\n",key); return 0;
}
struct node
{
int data;
struct node *previous;
struct node *next;
}
Operations on Double Linked List
In a double linked list, we perform the following operations...
1. Create
2. Insertion
3. Deletion
4. Display
5. Searching
1.Creation :
Before we implement actual operations, first we need to setup empty list. First perform the following steps
before implementing actual operations.
Step 1 - Include all the header files which are used in the program.
Step 2 - Declare all the user defined functions.
Step 3 - Define a Node structure with Three members previous, data and next
Step 4 - Define a Node pointer 'head' and set it to NULL.
Step 5 - Create a newNode with given value, Say "ptr".
Step 6- Check whether list is Empty (head == NULL).
Step 7- If it is Empty then, set head = ptr and define a Node pointer 'temp' and initialize with 'head'.
Step 8- If it is Not Empty then, set temp->next=ptr, ptr->previous=temp and temp =ptr.
Program:
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
struct node *previous;
};
struct node *head=NULL;
void create()
{
struct node *ptr,*temp;
int i,n,val;
printf("Enter Number of Elements :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
ptr=(struct node*)malloc(sizeof(struct node));
printf("Enter the data of node %d: ", i);
scanf("%d",&val);
ptr->data=val;
ptr->previous=NULL;
ptr->next=NULL;
if(head==NULL)
{
head=ptr;
temp=head;
}
else
{
temp->next=ptr;
ptr->previous=temp;
temp=ptr;
}
}
}
2.Insertion :
In a double linked list, the insertion operation can be performed in three ways as follows...
We can use the following steps to insert a new node at beginning of the double linked list...
Step 1 - Create a newNode with given value ,Say “ ptr “ and ptr → previous as
NULL. Step 2 - Check whether list is Empty (head == NULL)
Step 3 - If it is Empty then, assign NULL to ptr → next and ptr to head.
Step 4 - If it is not Empty then, assign head to ptr → next , ptr to head→ previous and ptr to head.
Program:
void insert_beg()
{
struct node *ptr;
int num;
ptr=(struct node*)malloc(sizeof(struct node));
printf("Enter data:");
scanf("%d",&num);
ptr->data=num;
ptr->previous=NULL;
if(head==NULL)
{
ptr->next = NULL;
head = ptr;
}
else
{
ptr->next = head;
head->previous=ptr;
head = ptr;
}
}
Step 1 - Create a newNode with given value ,Say “ ptr “ and ptr → next as NULL.
Step 3 - If it is Empty, then assign NULL to ptr → previous and ptr to head.
Step 4 - If it is not Empty, then, define a node pointer temp and initialize with head.
Step 5 - Keep moving the temp to its next node until it reaches to the last node in the list (until temp →
next is equal to NULL).
void insert_end()
{
struct node *ptr;
int num;
ptr=(struct node*)malloc(sizeof(struct node));
printf("Enter data:");
scanf("%d",&num);
ptr->data=num;
ptr->next=NULL;
if(head==NULL)
{
ptr->previous=NULL;
head=ptr;
}
else
{
struct Node *temp; temp=head;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=ptr;
ptr->previous=temp;
}
}
3.Deletion :
In a double linked list, the deletion operation can be performed in three ways
1. Deleting from Beginning of the list
2. Deleting from End of the list
3. Deleting a Specific Node
Deleting from Beginning of the list
We can use the following steps to delete a node from beginning of the double linked list...
Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate the function.
Step 3 - If it is not Empty then, define a Node pointer 'temp' and initialize with head.
Step 4 - Check whether list is having only one node (temp → previous is equal to temp → next).
Step 5 - If it is TRUE, then set head to NULL and delete temp (Setting Empty list conditions)
Step 6 - If it is FALSE, then assign temp → next to head, NULL to head → previous and delete temp.
Program:
void delete_beg()
{
if(head==NULL)
{
printf("List is Empty!!! Deletion is not possible\n");
}
else
{
struct node *temp;
temp=head;
if(temp->previous==temp->next)
{
head=NULL;
printf("Deleted element is %d",temp->data);
free(temp);
}
else
{
head =temp->next;
head->previous=NULL;
printf("Deleted element is %d",temp->data);
free(temp);
}
}
}
Program:
int delete_pos()
{
int pos,i=1;
if(head==NULL)
{
printf("List is Empty!!! Deletion is not possible\n");
}
else
{
4.Searching :
1. Initialize a node pointer, temp=head.
2. Input element to search from user. Store it in some variable say "key".
3. Declare a variable to store index of found element through list, say "count=0".
4. Do following while temp is not NULL
• temp->data == key , if the condition is true, The element is found.
• otherwise ,increment count ( count++) and move temp to its next node (temp = temp->next )
5.while temp is NULL, The element is not found.
Program:
int searchNode()
{
struct node *temp = head;
int key,count=0;
printf("\nEnter the element to be searched in the list : ");
scanf("%d",&key);
while(temp != NULL)
{
if(temp->data == key)
{
printf("\nElement %d found at position %d",key,count);
return 0;
}
else
{
count+=1;
temp = temp->next;
}
}
printf("\n Element %d is not found in the list\n",key);
return 0;
}
1. Creation :
Before we implement actual operations, first we need to setup empty list. First perform the following steps
before implementing actual operations.
Step 1 - Include all the header files which are used in the program.
Step 2 - Declare all the user defined functions.
Step 3 - Define a Node structure with two members data and next
Step 4 - Define a Node pointer 'head' and set it to NULL.
Step 5 - Create a newNode with given value, Say "ptr".
Step 6- Check whether list is Empty (head == NULL).
Step 7 - If it is Empty then, set head = ptr and ptr→next = head and define a Node pointer 'temp' and
initialize with 'head'.
Step 8- If it is Not Empty then, set temp->next=ptr, temp=ptr and temp->next=head.
Program:
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head=NULL;
void create()
{
struct node *ptr,*temp;
int i,n,val;
printf("Enter Number of Elements\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
ptr=(struct node*)malloc(sizeof(struct node));
printf("Enter the data of node %d: ", i);
scanf("%d",&val);
ptr->data=val;
if(head==NULL)
{
head=ptr;
ptr->next=head;
temp=head;
}
else
{
temp->next=ptr;
temp=ptr;
temp>next=head;
}
}
}
2.Insertion
In a circular linked list, the insertion operation can be performed in three ways. They are as follows...
1. Inserting At Beginning of the list
2. Inserting At End of the list
3. Inserting At Specific location in the list
}
else
{
temp=head;
if(temp->next==head)
{
temp->next=ptr;
ptr->next=temp;
}
else
{
while(temp->next!=head)
{
temp=temp->next;
}
temp->next=ptr;
ptr->next=head;
}
}
}
Step 5 - If it is TRUE. Then, set head = NULL and delete temp. And terminate from the function.
(Setting Empty list condition)
Step 6 - If it is FALSE. Then, set 'temp1 = temp ' and move temp to its next node. Repeat the same
until temp reaches to the last node in the list. (until temp → next == head)
Step 7 - Set temp1 → next = head and delete temp.
void delete_end()
{
if(head==NULL)
{
printf("List is Empty!!! Deletion is not possible\n");
}
else
{
}
else
{
while(temp->next!=head)
{
temp1=temp;
temp=temp->next;
}
temp1->next=head;
printf("Deleted element is %d",temp->data);
free(temp);
}
}
}
3. Deleting a Specific Node from the list
We can use the following steps to delete a specific node from the single linked list...
Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate the function.
Step 3 - If it is Not Empty then, define two Node pointers 'temp' and 't' and initialize 'temp'
with head.
Step 4- Traverse the nth Node.
Step 5- Finally, Set t=temp->next; and temp->next=t->next; t->next=NULL.and Delete " t"
Program:
int delete_pos()
{
int pos,i=1;
if(head==NULL)
{
printf("List is Empty!!! Deletion is not possible\n");
}
else
{ struct node *temp,*t;
temp=head;
printf("Enter position to delete:");
scanf("%d",&pos);
if(temp->next==NULL)
{
head=NULL;
printf("Deleted element is %d",temp->data);
free(temp);
}
else
{
while(i<pos-1)
{
temp=temp->next;
i++;
}
t=temp->next;
temp->next=t->next;
t->next=NULL;
printf("Deleted element is %d",t->data);
free(t);
}
}
return 0;
}
4. Displaying a circular Linked List
We can use the following steps to display the elements of a circular linked list...
Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty, then display 'List is Empty!!!' and terminate the function.
Step 3 - If it is Not Empty then, define a Node pointer 'temp' and initialize with head.
Step 4 - Keep displaying temp → data with an arrow (--->) until temp reaches to the last node
Step 5 - Finally display temp → data with arrow pointing to head → data.
Program:
void display()
{
if(head==NULL)
{
printf("List is Empty!!!\n");
}
else
{
struct node *temp;
temp=head;
printf("The linked list is:\n");
while(temp->next!=head)
{
printf("%d->",temp->data);
temp=temp->next;
}
printf("%d->%d",temp->data,head->data);
}
}
STACK ADT
• Stack is a linear data structure.
• Stack is a Collection of similar data items in which both insertion and deletion operations are performed
based on LIFO(Last In Last Out) principle.
• In stack, the insertion and deletion operations are performed at only one end called “top”.
• That means, a new element is added at top of the stack and an element is removed from the top of the
stack.
• In a stack, the insertion operation is performed using a function called "push" and deletion operation is
performed using a function called "pop".
Stack Representation:
A most popular example of stack is plates in marriage party. Fresh plates are pushed onto to the top and
popped from the top.
46
Operations on a Stack
The following operations are performed on the stack
1. Push (To insert an element on to the stack)
2. Pop (To delete an element from the stack)
3. Display (To display elements of the stack)
STACK IMPLEMENTATION
Stack data structure can be implemented in two ways. They are as follows...
1. Stack using Array
2. Stack using Linked List
• Step 1 - Include all the header files which are used in the program and define a constant 'SIZE' with
specific value.
• Step 2 - Declare all the functions used in stack implementation.
• Step 3 - Create a one dimensional array with fixed size (int stack[SIZE])
• Step 4 - Define a integer variable 'top' and initialize with '-1'. (int top = -1)
• Step 5 - In main method, display menu with list of operations and make suitable function calls to perform
operation selected by the user on the stack.
47
1.push(value) - Inserting value into the stack
• In a stack, push() is a function used to insert an element into the stack.
• In a stack, the new element is always inserted at top position.
• Push function takes one integer value as parameter and inserts that value into the stack.
Example
• If we want to create a stack by inserting 10,20,30 and 40.
• Then 10 becomes the bottom-most element and 40 is the top-most element.
• The last inserted element 40 is at Top of the stack as shown in the below figure.
3 3 3 3 top-> 3 40 top-> 3 40
2 2 2 top-> 2 30 2 30 2 30
1 1 top-> 1 20 1 20 1 20 1 20
0 top-> 0 10 0 10 0 10 0 10 0 10
if(top == SIZE-1)
48
printf("\nStack is Full!!! Insertion is not possible!!!");
else
top++;
stack[top] = value;
}
2.pop() - Delete a value from the Stack
• In a stack, pop() is a function used to delete an element from the stack.
• In a stack, the element is always deleted from top position.
• Pop function does not take any value as parameter.
We can use the following steps to pop an element from the stack...
• Step 1: Check whether stack is EMPTY. (top == -1)
• Step 2: If it is EMPTY, then display "Stack is EMPTY!!! Deletion is not possible!!!" and terminate the
function.
• Step 3: If it is NOT EMPTY, then delete stack[top] and decrement top value by one (top--).
Example:
3 3 3 3 3
top-> 2 30 2 2 2 2
1 20 top-> 1 20 1 1 1
0 10 0 10 top-> 0 10 0 0
49
void pop()
if(top == -1)
else
top--;
}
3.display() - Displays the elements of a Stack
We can use the following steps to display the elements of a stack...
void display()
if(top == -1)
printf("\nStack is Empty!!!");
else
int i;
printf("%d\n",stack[i]);
50
}
#include<stdio.h>
#include<conio.h>
#define SIZE 5
void push(int);
void pop();
void display();
void main()
clrscr();
while(1)
scanf("%d",&choice);
switch(choice)
scanf("%d",&value);
push(value);
break;
case 2: pop();
break;
51
case 3: display();
break;
case 4: exit(0);
if(top == SIZE-1)
else
top++;
stack[top] = value;
printf("\nInsertion success!!!");
void pop()
if(top == -1)
else
top--;
void display()
52
{
if(top == -1)
printf("\nStack is Empty!!!");
else
int i;
printf("%d\n",stack[i]);
53
Example
In the above example, the last inserted node is 90 and the first inserted node is 20. The order of elements
inserted is 20, 40,60 and 90.
void pop()
{
if(top == NULL)
printf("\nStack is Empty!!!\n");
else
{
struct node *temp = top;
printf("\nDeleted element: %d", temp->data);
top = temp->next;
free(temp);
}
55
}
void display()
{
if(top == NULL)
printf("\nStack is Empty!!!\n");
else
{
struct node *temp = top;
while(temp->next != NULL){
printf("%d--->",temp->data);
temp = temp -> next;
}
printf("%d--->NULL",temp->data);
}
}
56
}*top = NULL;
void push(int);
void pop();
void display();
void main()
{
int choice, value;
clrscr();
printf("\n:: Stack using Linked List ::\n");
while(1)
{
printf("\n****** MENU ******\n");
printf("1. Push\n2. Pop\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter the value to be insert: ");
scanf("%d", &value);
push(value);
break;
case 2: pop(); break;
case 3: display(); break;
case 4: exit(0);
default: printf("\nWrong selection!!! Please try again!!!\n");
}
}
}
void push(int value)
{
struct node *ptr;
ptr = (struct node*)malloc(sizeof(struct node));
57
ptr->data = value;
if(top == NULL)
ptr->next = NULL;
else
ptr->next = top;
top = ptr;
}
void pop()
{
if(top == NULL)
printf("\nStack is Empty!!!\n");
else
{
struct node *temp = top;
printf("\nDeleted element: %d", temp->data);
top = temp->next;
free(temp);
}
}
void display()
{
if(top == NULL)
printf("\nStack is Empty!!!\n");
else
{
struct node *temp = top;
while(temp->next != NULL)
{
printf("%d--->",temp->data);
temp = temp -> next;
}
printf("%d--->NULL",temp->data);
}
58
}
QUEUE ADT
Queue data structure is a collection of similar data items in which insertion and deletion operations are performed
based on FIFO(First In First Out) principle.
Queue is a linear data structure in which the insertion and deletion operations are performed at two different ends.
The insertion is performed at one end called ‘rear’ and deletion is performed at another end called ‘front’.
Operations on a Queue
The following operations are performed on a queue data structure...
Example
1) Initially front=rear=-1.It indicates Queue is empty 7) Delete(10 is removed)
0 1 2 3 0 1 2 3
20 30 40
front rear
2) Insert 10 0 1 2 3
10 8)Delete(20 is removed)
front rear 0 1 2 3
30 40
3) Insert 20 0 1 2 3 front rear
10 20
front rear 8)Delete(30 is removed)
0 1 2 3
4) Insert 30 0 1 2 3 40
10 20 30 front rear
front rear
9)Delete(40 is removed)
5) Inser 40 0 1 2 3 0 1 2 3
10 20 30 40
front rear front= rear=-1
QUEUE IMPLEMENTATION
Queue data structure can be implemented in two ways. They are as follows...
59
1.Queue Using Array
• A queue data structure can be implemented using one dimensional array.
• The queue implemented using array stores only fixed number of data values.
• Just define a one dimensional array of specific size and insert or delete the values into that array by
using FIFO (First In First Out) principle with the help of variables 'front' and 'rear'.
• Initially both 'front' and 'rear' are set to -1.
• Whenever, we want to insert a new value into the queue, increment 'rear' value by one and then insert at
that position.
• Whenever we want to delete a value from the queue, then delete the element which is at 'front' position
and increment 'front' value by one.
We can use the following steps to insert an element into the queue...
• Step 1 - Check whether queue is FULL. (rear == SIZE-1)
• Step 2 - If it is FULL, then display "Queue is FULL!!! Insertion is not possible!!!" and terminate the
function.
60
• Step 3 - If it is NOT FULL, then increment rear value by one (rear++) and set queue[rear] = value.
We can use the following steps to delete an element from the queue...
• Step 1 - Check whether queue is EMPTY. (front == rear)
• Step 2 - If it is EMPTY, then display "Queue is EMPTY!!! Deletion is not possible!!!" and terminate
the function.
• Step 3 - If it is NOT EMPTY, then increment the front value by one (front ++). Then
display queue[front] as deleted element. Then check whether both front and rear are equal
(front == rear), if it TRUE, then set both front and rear to '-1' (front = rear = -1).
void deQueue()
{
if(front == rear)
61
printf("\nQueue is Empty!!! Deletion is not possible!!!");
else
{
printf("\nDeleted : %d", queue[front]);
front++;
if(front == rear)
front = rear = -1;
}
}
void display()
{
if(rear == -1)
printf("\nQueue is Empty!!!");
else
{
int i;
printf("\nQueue elements are:\n");
for(i=front; i<=rear; i++)
printf("%d\t",queue[i]);
}
}
62
Implementation of Queue Datastructure using Array
#include<stdio.h>
#include<conio.h>
#define SIZE 10
void enQueue(int);
void deQueue();
void display();
int queue[SIZE], front = -1, rear = -1;
void main()
{
int value, choice;
clrscr();
while(1)
{
printf("\n\n***** MENU *****\n");
printf("1. Insertion\n2. Deletion\n3. Display\n4. Exit");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter the value to be insert: ");
scanf("%d",&value);
enQueue(value);
break;
case 2: deQueue();
break;
case 3: display();
break;
case 4: exit(0);
default: printf("\nWrong selection!!! Try again!!!");
}
}
}
63
void enQueue(int value)
{
if(rear == SIZE-1)
printf("\nQueue is Full!!! Insertion is not possible!!!");
else
{
if(front == -1)
front = 0;
rear++;
queue[rear] = value;
printf("\nInsertion success!!!");
}
}
void deQueue()
{
if(front == rear)
printf("\nQueue is Empty!!! Deletion is not possible!!!");
else
{
printf("\nDeleted : %d", queue[front]);
front++;
if(front == rear)
front = rear = -1;
}
}
void display()
{
if(rear == -1)
printf("\nQueue is Empty!!!");
else
{
int i;
printf("\nQueue elements are:\n");
64
for(i=front; i<=rear; i++)
printf("%d\t",queue[i]);
}
}
2.Queue Using Linked List
• The queue which is implemented using a linked list can work for an unlimited number of values.
• That means, queue using linked list can work for the variable size of data (No need to fix the size at the
beginning of the implementation).
• The Queue implemented using linked list can organize as many data values as we want.
In linked list implementation of a queue, the last inserted node is always pointed by 'rear' and the first
node is always pointed by 'front'.
Example
• In above example, the last inserted node is 50 and it is pointed by 'rear' and the first inserted node is 10
and it is pointed by 'front'.
• The order of elements inserted is 10, 15, 22 and 50.
Queue Operations
To implement queue using linked list, we need to set the following things before implementing actual operations.
• Step 1 - Include all the header files which are used in the program. And declare all the user defined
functions.
• Step 2 - Define a 'Node' structure with two members data and next.
• Step 3 - Define two Node pointers 'front' and 'rear' and set both to NULL.
• Step 4 - Implement the main method by displaying Menu of list of operations and make suitable function
calls in the main method to perform user selected operation.
65
• Step 1 - Create a newNode say ‘ptr’ with given value and set 'ptr → next' to NULL.
• Step 2 - Check whether queue is Empty (rear == NULL)
• Step 3 - If it is Empty then, set front = ptr and rear = rear.
• Step 4 - If it is Not Empty then, set rear → next = ptr and rear = ptr.
void delete()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
66
else
{
struct node *temp = front;
front = front -> next;
printf("\nDeleted element: %d\n", temp->data);
free(temp);
}
}
void display()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else
{
struct Node *temp = front;
while(temp->next != NULL){
printf("%d--->",temp->data);
temp = temp -> next;
}
printf("%d--->NULL\n",temp->data);
}
}
67
Implementation of Queue Datastructure using Linked List
#include<stdio.h>
#include<conio.h>
struct node
{
int data;
struct node *next;
}*front = NULL,*rear = NULL;
void insert(int);
void delete();
void display();
void main()
{
int choice, value;
clrscr();
printf("\n:: Queue Implementation using Linked List ::\n");
while(1)
{
printf("\n****** MENU ******\n");
printf("1. Insert\n2. Delete\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter the value to be insert: ");
scanf("%d", &value);
insert(value);
break;
case 2: delete(); break;
case 3: display(); break;
case 4: exit(0);
default: printf("\nWrong selection!!! Please try again!!!\n");
68
}
}
}
void insert(int value)
{
struct node *ptr;
ptr = (struct node*)malloc(sizeof(struct node));
ptr->data = value;
ptr -> next = NULL;
if(front == NULL)
front = rear = ptr;
else
{
rear -> next = ptr;
rear = ptr;
}
}
void delete()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else
{
struct node *temp = front;
front = front -> next;
printf("\nDeleted element: %d\n", temp->data);
free(temp);
}
}
void display()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
69
else
{
struct node *temp = front;
while(temp->next != NULL)
{
printf("%d--->",temp->data);
temp = temp -> next;
}
printf("%d--->NULL\n",temp->data);
}
}
STACK APPLICATIONS
Stacks can be used for Conversion from one form of expression to another.
What is an Expression?
Every expression can be represented using all the above three different types of expressions.
70
we can convert an expression from one form to another form like
4. Balancing of Symbols
b)If the stack is not Empty, check the priority of the operator
i ) If scan operator is higher priority than the top of stack operator then scanned
ii) If scan operator is same or lower priority than the top of stack operator then pop the
operator from the stack and add to postfix expression and scanned operator will
5. If the character is RIGHT PARANTHESIS, then pop all the operators from the stack until it reaches
Scanne Postfix
S.N Operstion Stack
d Expressi
o
Charact on
er
72
Example 2 : Convert A + ( B * C ) to postfix expression.
Postfix
S.N Scanned Operation Stack
Expressi
o Character
on
+ Push '+' + A
2
( Push '(' +( A
3
Postfix
S.N Scanned Operation Stack
Expressi
o Character
on
73
+'
Scanne Postfix
S.N Operation Stack
d Expressi
o Charact on
er
( Push ' ( ' ( Nothing
1
74
16 F Add to postfix 'F' -*( AB+C*DE-F
17 + Push ' + ' -*(+ AB+C*DE-F
18 G Add to postfix 'G' -*(+ AB+C*DE-FG
Pop ' + ' and add to
19 ) -* AB+C*DE-
postfix ' + '
FG+
Pop all the operators
20 NIL from the stack and STACK IS AB+C*DE-
L add to postfix EMPTY FG+*-
expression
( A + B ) * C - ( D - E ) * ( F + G ) = AB+C*DE-FG+*-
i ) If scan operator is same or higher priority than the top of stack , scanned
ii) If scan operator is lower priority than the top of stack , pop the operator from the
stack and add to prefix expression and scanned operator will push on stack,
Repeat step 4.
5. If the character is CLOSING PARANTHESIS, then push operator into the stack.
6. If the character is OPEN PARANTHESIS, then pop all the operators from the stack until it reaches
CLOSING PARANTHESIS and ADD to prefix expression.pop and discard the closing parenthesis.
7. After reading all characters, if stack is not empty then pop and ADD to prefix expression
8. Reverse the output string.
75
Example 1 : Convert A + B to prefix expression. Solution
Prefix
S.N Scanned Operation Stack
Expressi
o Character
on
1 B Add to prefix 'B' Stack is B
Empty
2 + Push ' + ' + B
3 A Add to prefix 'A' + BA
Pop all the operators
4 Nill from the stack and Stack is BA+
add to prefix Empty
expression
5 Reverse the output +AB
string
76
9 Reverse the output +A*BA
string
77
8 E Add to prefix 'E' *) GF+E
9 - Push ' - ' *)- GF+E
10 D Add to prefix 'D' *)- GF+ED
Pop all the operators
11 ( until * GF+ED-
closing parenthesis and
Add to prefix '-'
Pop ' * 'and add to
12 - - GF+ED-*
prefix '* '.
push '-'
13 C Add to prefix 'C' - GF+ED-*C
14 * Push ' * ' -* GF+ED-*C
15 ) Push ' ) ' -*) GF+ED-*C
16 B Add to prefix 'B' -*) GF+ED-*CB
17 + Push ' + ' - * )+ GF+ED-*CB
18 A Add to prefix 'A' - * )+ GF+ED-*CBA
Pop all the operators
19 ( until -* GF+ED-*CBA+
closing parenthesis and
Add to prefix '+'
Pop all the operators
Stack
20 Nill from the stack and add GF+ED-
is
to prefix *CBA+*-
Empty
expression
21 Reverse the output - * + ABC*-
string DE+FG
Postfix Expression : If the operator is used after operands are called Postfix expression.
To evaluate a postfix expression using Stack data structure we can use the following steps...
78
1. Read an Expression from left to right.
3. If the character is OPERATOR, POP top two operands from the stack perform calculation and PUSH
the result back into stack.
4.After reading the characters from the postfix expression stack will be having only the value which is
result.
53+82-*
Scanned Evaluated
S.N Operations
Character Stac Part of
o k
/ Symbol Expression
Nothing
5
2 Push ( 5 )
5
3 Nothing
3 3 Push ( 3 ) 5
79
value1 =5
value2 =3
4 + pop two operands
8 (5 + 3) = 8
5 8 Push ( 8 ) 8
(5 + 3) = 8
8
8 (5 + 3) = 8
6 2 Push ( 2 )
8
value1=2
value2=8
7 pop two operands 6
(8-2)=6
-
8
value1=6
value2=8
8 pop two operands (8 * 6)=48
*
48
80
Balancing of symbols : The objective of this application is to check the Symbols such as
parenthesis ( and ), Square brackets [ and ] and Curly braces { and } are matched or not. The algorithm is
very much useful in compilers.
We know in a valid expression the parenthesis, Square brackets , Curly braces must occur in
pairs. that is when there is an opening parenthesis, Square brackets , Curly braces there should be
corresponding closing parenthesis. Otherwise , the expression is not a valid.
Examples:
3. If the character is an opening Symbol like ‘(‘ , ‘{‘ or ‘[‘ then it is PUSHED in to the stack.
4. If the character is an closing Symbol like ' ) ' , ' } ' , ' ] ' , then
a ) If the stack is empty then report as unbalanced expression otherwise pop from the stack .
b ) if the symbol popped is not the corresponding open symbol then report as unbalanced
expression
5. After reading all the characters are processed, if the stack is not empty report as unbalanced
Example 2 : Check whether the expression is balanced symbol or not ((A+B) + (C-D)
DATA STRUCTURES
ASSIGNMENT - 1
-1)+5*(4-1)
-1)+5*(4-1)
83
DATA STRUCTURES
ASSIGNMENT - 1
-1)+5*(4-1)
-1)+5*(4-1)
84
85
86