SlideShare une entreprise Scribd logo
1  sur  89
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
UNIT II : LINEAR DATA STRUCTURES – LIST
Abstract Data Types (ADTs) – List ADT – array-based implementation – linked list
implementation ––singly linked lists- circularly linked lists- doubly-linked lists – Stack ADT-
Queue ADT- applications of queues.
Data Structure
The data structure name indicates itself that organizing the data in memory. There are many
ways of organizing the data in the memory as we have already seen one of the data structures, i.e.,
array in C language. Array is a collection of memory elements in which data is stored sequentially,
i.e., one after another. In other words, we can say that array stores the elements in a continuous
manner. This organization of data is done with the help of an array of data structures. There are
also other ways to organize the data in memory. Let's see the different types of data structures.
The data structure is not any programming language like C, C++, java, etc. It is a set of
algorithms that we can use in any programming language to structure the data in the memory.
To structure the data in memory, 'n' number of algorithms were proposed, and all these
algorithms are known as Abstract data types. These abstract data types are the set of rules.
Types of Data Structures
There are two types of data structures:
Primitive data structure
Non-primitive data structure
Primitive Data structure
The primitive data structures are primitive data types. The int, char, float, double, and
pointer are the primitive data structures that can hold a single value.
Non-Primitive Data structure
The non-primitive data structure is divided into two types:
Linear data structure
Non-linear data structure
Linear Data Structure
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
The arrangement of data in a sequential manner is known as a linear data structure. The
data structures used for this purpose are Arrays, Linked list, Stacks, and Queues. In these data
structures, one element is connected to only one another element in a linear form.
When one element is connected to the 'n' number of elements known as a non-linear
data structure. The best example is trees and graphs. In this case, the elements are arranged
in a random manner.
We will discuss the above data structures in brief in the coming topics. Now, we will see
the common operations that we can perform on these data structures.
Data structures can also be classified as:
Static data structure: It is a type of data structure where the size is allocated at the compile
time. Therefore, the maximum size is fixed.
Dynamic data structure: It is a type of data structure where the size is allocated at the run
time. Therefore, the maximum size is flexible.
Major Operations
The major or the common operations that can be performed on the data structures are:
Searching: We can search for any element in a data structure.
Sorting: We can sort the elements of a data structure either in an ascending or descending
order.
Insertion: We can also insert the new element in a data structure.
Updation: We can also update the element, i.e., we can replace the element with another
element.
Deletion: We can also perform the delete operation to remove the element from the data
structure.
Which Data Structure?
A data structure is a way of organizing the data so that it can be used efficiently. Here, we
have used the word efficiently, which in terms of both the space and time. For example, a stack is
an ADT (Abstract data type) which uses either arrays or linked list data structure for the
implementation. Therefore, we conclude that we require some data structure to implement a
particular ADT.
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
An ADT tells what is to be done and data structure tells how it is to be done. In other words,
we can say that ADT gives us the blueprint while data structure provides the implementation part.
Now the question arises: how can one get to know which data structure to be used for a particular
ADT?.
As the different data structures can be implemented in a particular ADT, but the different
implementations are compared for time and space. For example, the Stack ADT can be
implemented by both Arrays and linked list. Suppose the array is providing time efficiency while
the linked list is providing space efficiency, so the one which is the best suited for the current user's
requirements will be selected.
Advantages of Data structures
The following are the advantages of a data structure:
Efficiency: If the choice of a data structure for implementing a particular ADT is proper,
it makes the program very efficient in terms of time and space.
Reusability: he data structures provide reusability means that multiple client programs can
use the data structure.
Abstraction: The data structure specified by an ADT also provides the level of abstraction.
The client cannot see the internal working of the data structure, so it does not have to worry about
the implementation part. The client can only see the interface.
Basic Terminology:
Data structures are the building blocks of any program or the software. Choosing the
appropriate data structure for a program is the most difficult task for a programmer. Following
terminology is used as far as data structures are concerned
Data: Data can be defined as an elementary value or the collection of values, for example,
student's name and its id are the data about the student.
Group Items: Data items which have subordinate data items are called Group item, for
example, name of a student can have first name and the last name.
Record: Record can be defined as the collection of various data items, for example, if we
talk about the student entity, then its name, address, course and marks can be grouped together to
form the record for the student.
File: A File is a collection of various records of one type of entity, for example, if there are
60 employees in the class, then there will be 20 records in the related file where each record
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
contains the data about each employee.
Attribute and Entity: An entity represents the class of certain objects. it contains various
attributes. Each attribute represents the particular property of that entity.
Field: Field is a single elementary unit of information representing the attribute of an
entity.
Need of Data Structures
As applications are getting complexed and amount of data is increasing day by day, there
may arrise the following problems:
Processor speed: To handle very large amout of data, high speed processing is required,
but as the data is growing day by day to the billions of files per entity, processor may fail to deal
with that much amount of data.
Data Search: Consider an inventory size of 106 items in a store, If our application needs
to search for a particular item, it needs to traverse 106 items every time, results in slowing down
the search process.
Multiple requests: If thousands of users are searching the data simultaneously on a web
server, then there are the chances that a very large server can be failed during that process
in order to solve the above problems, data structures are used. Data is organized to form a
data structure in such a way that all items are not required to be searched and required data can be
searched instantly.
Advantages of Data Structures
Efficiency: Efficiency of a program depends upon the choice of data structures. For
example: suppose, we have some data and we need to perform the search for a perticular record.
In that case, if we organize our data in an array, we will have to search sequentially element by
element. hence, using array may not be very efficient here. There are better data structures which
can make the search process efficient like ordered array, binary search tree or hash tables.
Reusability: Data structures are reusable, i.e. once we have implemented a particular data
structure, we can use it at any other place. Implementation of data structures can be compiled into
libraries which can be used by different clients.
Abstraction: Data structure is specified by the ADT which provides a level of abstraction.
The client program uses the data structure through interface only, without getting into the
implementation details.
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
Data Structure Classification
Linear Data Structures: A data structure is called linear if all of its elements are arranged
in the linear order. In linear data structures, the elements are stored in non-hierarchical way where
each element has the successors and predecessors except the first and last element.
Types of Linear Data Structures are given below:
Arrays: An array is a collection of similar type of data items and each data item is called
an element of the array. The data type of the element may be any valid data type like char, int, float
or double.
The elements of array share the same variable name but each one carries a different index
number known as subscript. The array can be one dimensional, two dimensional or
multidimensional.
The individual elements of the array age are:
age[0], age[1], age[2], age[3],......... age[98], age[99].
Linked List: Linked list is a linear data structure which is used to maintain a list in the
memory. It can be seen as the collection of nodes stored at non-contiguous memory locations. Each
node of the list contains a pointer to its adjacent node.
Stack: Stack is a linear list in which insertion and deletions are allowed only at one end,
called top.
A stack is an abstract data type (ADT), can be implemented in most of the programming
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
languages. It is named as stack because it behaves like a real-world stack, for example: - piles of
plates or deck of cards etc.
Queue: Queue is a linear list in which elements can be inserted only at one end
called rear and deleted only at the other end called front.
It is an abstract data structure, similar to stack. Queue is opened at both end therefore it
follows First-In-First-Out (FIFO) methodology for storing the data items.
Non Linear Data Structures: This data structure does not form a sequence i.e. each item
or element is connected with two or more other items in a non-linear arrangement. The data
elements are not arranged in sequential structure.
Types of Non Linear Data Structures are given below:
Trees: Trees are multilevel data structures with a hierarchical relationship among its
elements known as nodes. The bottommost nodes in the herierchy are called leaf node while the
topmost node is called root node. Each node contains pointers to point adjacent nodes.
Tree data structure is based on the parent-child relationship among the nodes. Each node
in the tree can have more than one children except the leaf nodes whereas each node can have
atmost one parent except the root node. Trees can be classfied into many categories which will be
discussed later in this tutorial.
Graphs: Graphs can be defined as the pictorial representation of the set of elements
(represented by vertices) connected by the links known as edges. A graph is different from tree in
the sense that a graph can have cycle while the tree can not have the one.
Operations on data structure
1) Traversing: Every data structure contains the set of data elements. Traversing the data
structure means visiting each element of the data structure in order to perform some specific
operation like searching or sorting.
Example: If we need to calculate the average of the marks obtained by a student in 6
different subject, we need to traverse the complete array of marks and calculate the total sum, then
we will devide that sum by the number of subjects i.e. 6, in order to find the average.
2) Insertion: Insertion can be defined as the process of adding the elements to the data
structure at any location.
If the size of data structure is n then we can only insert n-1 data elements into it.
3) Deletion:The process of removing an element from the data structure is called Deletion.
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
We can delete an element from the data structure at any random location.
If we try to delete an element from an empty data structure then underflow occurs.
4) Searching: The process of finding the location of an element within the data structure
is called Searching. There are two algorithms to perform searching, Linear Search and Binary
Search. We will discuss each one of them later in this tutorial.
5) Sorting: The process of arranging the data structure in a specific order is known as
Sorting. There are many algorithms that can be used to perform sorting, for example, insertion sort,
selection sort, bubble sort, etc.
6) Merging: When two lists List A and List B of size M and N respectively, of similar type
of elements, clubbed or joined to produce the third list, List C of size (M+N), then this process is
called merging
Abstract Data Types
An abstract data type (ADT) is a set of operations. Abstract data types are mathematical
abstractions; ADT's defines how the set of operations is implemented. This can be viewed as an
extension of modular design.
Objects such as lists, sets, and graphs, along with their operations, can be viewed as abstract
data types, just as integers, reals, and booleans are data types.
Use of ADT
Reusability of the code, that the implementation of these operations is written once in the
program, and any other part of the program that needs to perform an operation on the ADT can do
so by calling the appropriate function.
The List ADT
A general list of the form a1, a2, a3, . . . , an. We say that the size of this list is n. We will
call the special list of size 0 a null list. For any list except the null list, we say that ai+l follows (or
succeeds) ai (i < n) and that ai-1 precedes ai (i > 1).
The first element of the list is a1, and the last element is an. there is no predecessor of a1 or
the successor of an. The position of element ai in a list is i.
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
Some operations in list are,
1. Find, which returns the position of the first occurrence of a key;
2. Insert and delete, which generally insert and delete some key from some position in
the list;
3. Find_kth, which returns the element in some position (specified as an argument).
Example:
1. If the list is 34, 12, 52, 16, 12, then find(52) might return 3;
2. Insert(x,3) might make the list into 34, 12, 52, x, 16, 12 (if we insert after the position given);
3. Delete (3) might turn that list into 34, 12, x, 16, 12.
Linked List
Linked lists and arrays are similar since they both store collections of data. Array is the most
common data structure used to store collections of elements. Arrays are convenient to declare and
provide the easy syntax to access any element by its index number. Once the array is set up, access
to any element is convenient and fast.
The disadvantages of arrays are:
• The size of the array is fixed. Most often this size is specified at compile time. This makes
the programmers to allocate arrays, which seems "large enough" than required.
• Inserting new elements at the front is potentially expensive because existing elements need
to be shifted over to make room.
• Deleting an element from an array is not possible. Linked lists have their own strengths
and weaknesses, but they happen to be strong where arrays are weak.
● Generally array's allocates the memory for all its elements in one block whereas linked lists
use an entirely different strategy. Linked lists allocate memory for each element separately
and only when necessary.
Linked List Concepts:
A linked list is a non-sequential collection of data items. It is a dynamic data structure. For every
data item in a linked list, there is an associated pointer that would give the memory location of the
next data item in the linked list. The data items in the linked list are not in consecutive memory
locations. They may be anywhere, but the accessing of these data items is easier as each data item
contains the address of the next data item.
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
Advantages of linked lists:
Linked lists have many advantages. Some of the very important advantages are:
1. Linked lists are dynamic data structures. i.e., they can grow or shrink during the execution of
a program.
2. Linked lists have efficient memory utilization. Here, memory is not preallocated. Memory is
allocated whenever it is required and it is de-allocated (removed) when it is no longer
needed.
3. Insertion and Deletions are easier and efficient. Linked lists provide flexibility in inserting a
data item at a specified position and deletion of the data item from the given position.
4. Many complex applications can be easily carried out with linked lists.
Disadvantages of linked lists:
1. It consumes more space because every node requires a additional pointer to store address
of the next node.
2. Searching a particular element in list is difficult and also time consuming.
Types of Linked Lists:
Basically we can put linked lists into the following four items:
1. Single Linked List.
2. Double Linked List.
3. Circular Linked List.
4. Circular Double Linked List.
A single linked list is one in which all nodes are linked together in some sequential manner. Hence,
it is also called as linear linked list.
A double linked list is one in which all nodes are linked together by multiple links which helps in
accessing both the successor node (next node) and predecessor node (previous node) from any
arbitrary node within the list. Therefore each node in a double linked list has two link fields
(pointers) to point to the left node (previous) and the right node (next). This helps to traverse in
forward direction and backward direction.
A circular linked list is one, which has no beginning and no end. A single linked list can be made
a circular linked list by simply storing address of the very first node in the link field of the last
node.A circular double linked list is one, which has both the successor pointer and predecessor
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
pointer in the circular manner.
Applications of linked list:
1. Linked lists are used to represent and manipulate polynomial. Polynomials are expression
containing terms with non zero coefficient and exponents. For example: P(x) = a0 Xn + a1
Xn-1 + …… + an-1 X + an
2. Represent very large numbers and operations of the large number such as addition,
multiplication and division.
3. Linked lists are to implement stack, queue, trees and graphs. 4. Implement the symbol table in
compiler construction.
Single Linked List:
A linked list allocates space for each element separately in its own block of memory called a
"node". The list gets an overall structure by using pointers to connect all its nodes together like the
links in a chain. Each node contains two fields; a "data" field to store whatever element, and a
"next" field which is a pointer used to link to the next node. Each node is allocated in the heap
using malloc(), so the node memory continues to exist until it is explicitly de-allocated using free().
The front of the list is a pointer to the “start” node.
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
A single linked list
The beginning of the linked list is stored in a "start" pointer which points to the first node. The first
node contains a pointer to the second node. The second node contains a pointer to the third node,
... and so on. The last node in the list has its next field set to NULL to mark the end of the list.
Code can access any node in the list by starting at the start and following the next pointers.
The start pointer is an ordinary local pointer variable, so it is drawn separately on the left top to
show that it is in the stack. The list nodes are drawn on the right to show that they are allocated in
the heap.
The basic operations in a single linked list are:
• Creation.
• Insertion.
• Deletion.
• Traversing.
Creating a node for Single Linked List:
Creating a singly linked list starts with creating a node. Sufficient memory has to be allocated for
creating a node. The information is stored in the memory.
Insertion of a Node:
One of the most primitive operations that can be done in a singly linked list is the insertion of a
node. Memory is to be allocated for the new node (in a similar way that is done while creating a
list) before reading the data. The new node will contain empty data field and empty next field. The
data field of the new node is then stored with the information read from the user. The next field of
the new node is assigned to NULL. The new node can then be inserted at three different places
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
namely:
• Inserting a node at the beginning.
• Inserting a node at the end.
• Inserting a node at intermediate position.
● Inserting a node at the beginning.
● Inserting a node at the end:
● Inserting a node into the single linked list at a specified intermediate position other than
beginning and end.
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
Deletion of a node:
Another primitive operation that can be done in a singly linked list is the deletion of a node.
Memory is to be released for the node to be deleted. A node can be deleted from the list from three
different places namely.
• Deleting a node at the beginning.
• Deleting a node at the end.
• Deleting a node at intermediate position.
Deleting a node at the beginning:
Deleting a node at the end:
Deleting a node at Intermediate position:
The following steps are followed, to delete a node from an intermediate position in the list (List
must contain more than two node).
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
Traversal and displaying a list (Left to Right):
To display the information, you have to traverse (move) a linked list, node by node from the
first node, until the end of the list is reached.
Traversing a list involves the following steps:
• Assign the address of start pointer to a temp pointer.
• Display the information from the data field of each node. The function traverse () is used for
traversing and displaying the information stored in the list from left to right.
Singly Linked List Implementation
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head;
void beginsert ();
void lastinsert ();
void randominsert();
void begin_delete();
void last_delete();
void random_delete();
void display();
void search();
void main ()
{
int choice =0;
while(choice != 9)
{
printf("nn*********Main Menu*********n");
printf("nChoose one option from the following list ...n");
printf("n===============================================n");
printf("n1.Insert in beginingn2.Insert at lastn3.Insert at any random locationn4.Delete from
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
Beginningn
5.Delete from lastn6.Delete node after specified locationn7.Search for an
elementn8.Shown9.Exitn");
printf("nEnter your choice?n");
scanf("n%d",&choice);
switch(choice)
{
case 1:
beginsert();
break;
case 2:
lastinsert();
break;
case 3:
randominsert();
break;
case 4:
begin_delete();
break;
case 5:
last_delete();
break;
case 6:
random_delete();
break;
case 7:
search();
break;
case 8:
display();
break;
case 9:
exit(0);
break;
default:
printf("Please enter valid choice..");
}
}
}
void beginsert()
{
struct node *ptr;
int item;
ptr = (struct node *) malloc(sizeof(struct node *));
if(ptr == NULL)
{
printf("nOVERFLOW");
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
}
else
{
printf("nEnter valuen");
scanf("%d",&item);
ptr->data = item;
ptr->next = head;
head = ptr;
printf("nNode inserted");
}
}
void lastinsert()
{
struct node *ptr,*temp;
int item;
ptr = (struct node*)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("nOVERFLOW");
}
else
{
printf("nEnter value?n");
scanf("%d",&item);
ptr->data = item;
if(head == NULL)
{
ptr -> next = NULL;
head = ptr;
printf("nNode inserted");
}
else
{
temp = head;
while (temp -> next != NULL)
{
temp = temp -> next;
}
temp->next = ptr;
ptr->next = NULL;
printf("nNode inserted");
}
}
}
void randominsert()
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
{
int i,loc,item;
struct node *ptr, *temp;
ptr = (struct node *) malloc (sizeof(struct node));
if(ptr == NULL)
{
printf("nOVERFLOW");
}
else
{
printf("nEnter element value");
scanf("%d",&item);
ptr->data = item;
printf("nEnter the location after which you want to insert ");
scanf("n%d",&loc);
temp=head;
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL)
{
printf("ncan't insertn");
return;
}
}
ptr ->next = temp ->next;
temp ->next = ptr;
printf("nNode inserted");
}
}
void begin_delete()
{
struct node *ptr;
if(head == NULL)
{
printf("nList is emptyn");
}
else
{
ptr = head;
head = ptr->next;
free(ptr);
printf("nNode deleted from the begining ...n");
}
}
void last_delete()
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
{
struct node *ptr,*ptr1;
if(head == NULL)
{
printf("nlist is empty");
}
else if(head -> next == NULL)
{
head = NULL;
free(head);
printf("nOnly node of the list deleted ...n");
}
else
{
ptr = head;
while(ptr->next != NULL)
{
ptr1 = ptr;
ptr = ptr ->next;
}
ptr1->next = NULL;
free(ptr);
printf("nDeleted Node from the last ...n");
}
}
void random_delete()
{
struct node *ptr,*ptr1;
int loc,i;
printf("n Enter the location of the node after which you want to perform deletion n");
scanf("%d",&loc);
ptr=head;
for(i=0;i<loc;i++)
{
ptr1 = ptr;
ptr = ptr->next;
if(ptr == NULL)
{
printf("nCan't delete");
return;
}
}
ptr1 ->next = ptr ->next;
free(ptr);
printf("nDeleted node %d ",loc+1);
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
}
void search()
{
struct node *ptr;
int item,i=0,flag;
ptr = head;
if(ptr == NULL)
{
printf("nEmpty Listn");
}
else
{
printf("nEnter item which you want to search?n");
scanf("%d",&item);
while (ptr!=NULL)
{
if(ptr->data == item)
{
printf("item found at location %d ",i+1);
flag=0;
}
else
{
flag=1;
}
i++;
ptr = ptr -> next;
}
if(flag==1)
{
printf("Item not foundn");
}
}
}
void display()
{
struct node *ptr;
ptr = head;
if(ptr == NULL)
{
printf("Nothing to print");
}
else
{
printf("nprinting values . . . . .n");
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
while (ptr!=NULL)
{
printf("n%d",ptr->data);
ptr = ptr -> next;
}
}
}
Output:
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete node after specified location
7.Search for an element
8.Show
9.Exit
Enter your choice?
1
Enter value
1
Node inserted
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete node after specified location
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
7.Search for an element
8.Show
9.Exit
Enter your choice?
2
Enter value?
2
Node inserted
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete node after specified location
7.Search for an element
8.Show
9.Exit
Enter your choice?
3
Enter element value1
Enter the location after which you want to insert 1
Node inserted
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
5.Delete from last
6.Delete node after specified location
7.Search for an element
8.Show
9.Exit
Enter your choice?
8
printing values . . . . .
1
2
1
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete node after specified location
7.Search for an element
8.Show
9.Exit
Enter your choice?
2
Enter value?
123
Node inserted
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete node after specified location
7.Search for an element
8.Show
9.Exit
Enter your choice?
1
Enter value
1234
Node inserted
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete node after specified location
7.Search for an element
8.Show
9.Exit
Enter your choice?
4
Node deleted from the begining ...
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
5.Delete from last
6.Delete node after specified location
7.Search for an element
8.Show
9.Exit
Enter your choice?
5
Deleted Node from the last ...
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete node after specified location
7.Search for an element
8.Show
9.Exit
Enter your choice?
6
Enter the location of the node after which you want to perform deletion
1
Deleted node 2
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete node after specified location
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
7.Search for an element
8.Show
9.Exit
Enter your choice?
8
printing values . . . . .
1
1
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete node after specified location
7.Search for an element
8.Show
9.Exit
Enter your choice?
7
Enter item which you want to search?
1
item found at location 1
item found at location 2
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
6.Delete node after specified location
7.Search for an element
8.Show
9.Exit
Enter your choice?
9
Double Linked List: A double linked list is a two-way list in which all nodes will have two links.
This helps in accessing both successor node and predecessor node from the given node position. It
provides bi- directional traversing. Each node contains three fields:
● Left link.
● Data.
● Right link.
The left link points to the predecessor node and the right link points to the successor node. The
data field stores the required data.
Many applications require searching forward and backward thru nodes of a list. For example
searching for a name in a telephone directory would need forward and backward scanning thru a
region of the whole list.
The basic operations in a double linked list are:
● Creation.
● Insertion.
● Deletion.
● Traversing.
The beginning of the double linked list is stored in a "start" pointer which points to the first
node. The first node‟s left link and last node‟s right link is set to NULL.
Creating a node for Double Linked List:
Creating a double linked list starts with creating a node. Sufficient memory has to be
allocated for creating a node. The information is stored in the memory.
Double Linked List with 3 nodes:
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
Inserting a node at the beginning:
Inserting a node at the end:
Inserting a node at an intermediate position:
Deleting a node at the beginning:
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
Deleting a node at the end:
Deleting a node at Intermediate position:
Traversal and displaying a list (Left to Right):
To display the information, you have to traverse the list, node by node from the first node, until
the end of the list is reached. The function traverse_left_right() is used for traversing and
displaying the information stored in the list from left to right.
Traversal and displaying a list (Right to Left):
To display the information from right to left, you have to traverse the list, node by node from the
first node, until the end of the list is reached. The function traverse_right_left() is used for
traversing and displaying the information stored in the list from right to left.
Menu Driven Program in C to implement all the operations of doubly linked list
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
#include<stdio.h>
#include<stdlib.h>
struct node
{
struct node *prev;
struct node *next;
int data;
};
struct node *head;
void insertion_beginning();
void insertion_last();
void insertion_specified();
void deletion_beginning();
void deletion_last();
void deletion_specified();
void display();
void search();
void main ()
{
int choice =0;
while(choice != 9)
{
printf("n*********Main Menu*********n");
printf("nChoose one option from the following list ...n");
printf("n===============================================n");
printf("n1.Insert in beginingn2.Insert at lastn3.Insert at any random locationn4.Delete from
Beginningn
5.Delete from lastn6.Delete the node after the given datan7.Searchn8.Shown9.Exitn");
printf("nEnter your choice?n");
scanf("n%d",&choice);
switch(choice)
{
case 1:
insertion_beginning();
break;
case 2:
insertion_last();
break;
case 3:
insertion_specified();
break;
case 4:
deletion_beginning();
break;
case 5:
deletion_last();
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
break;
case 6:
deletion_specified();
break;
case 7:
search();
break;
case 8:
display();
break;
case 9:
exit(0);
break;
default:
printf("Please enter valid choice..");
}
}
}
void insertion_beginning()
{
struct node *ptr;
int item;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("nOVERFLOW");
}
else
{
printf("nEnter Item value");
scanf("%d",&item);
if(head==NULL)
{
ptr->next = NULL;
ptr->prev=NULL;
ptr->data=item;
head=ptr;
}
else
{
ptr->data=item;
ptr->prev=NULL;
ptr->next = head;
head->prev=ptr;
head=ptr;
}
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
printf("nNode insertedn");
}
}
void insertion_last()
{
struct node *ptr,*temp;
int item;
ptr = (struct node *) malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("nOVERFLOW");
}
else
{
printf("nEnter value");
scanf("%d",&item);
ptr->data=item;
if(head == NULL)
{
ptr->next = NULL;
ptr->prev = NULL;
head = ptr;
}
else
{
temp = head;
while(temp->next!=NULL)
{
temp = temp->next;
}
temp->next = ptr;
ptr ->prev=temp;
ptr->next = NULL;
}
}
printf("nnode insertedn");
}
void insertion_specified()
{
struct node *ptr,*temp;
int item,loc,i;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("n OVERFLOW");
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
}
else
{
temp=head;
printf("Enter the location");
scanf("%d",&loc);
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL)
{
printf("n There are less than %d elements", loc);
return;
}
}
printf("Enter value");
scanf("%d",&item);
ptr->data = item;
ptr->next = temp->next;
ptr -> prev = temp;
temp->next = ptr;
temp->next->prev=ptr;
printf("nnode insertedn");
}
}
void deletion_beginning()
{
struct node *ptr;
if(head == NULL)
{
printf("n UNDERFLOW");
}
else if(head->next == NULL)
{
head = NULL;
free(head);
printf("nnode deletedn");
}
else
{
ptr = head;
head = head -> next;
head -> prev = NULL;
free(ptr);
printf("nnode deletedn");
}
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
}
void deletion_last()
{
struct node *ptr;
if(head == NULL)
{
printf("n UNDERFLOW");
}
else if(head->next == NULL)
{
head = NULL;
free(head);
printf("nnode deletedn");
}
else
{
ptr = head;
if(ptr->next != NULL)
{
ptr = ptr -> next;
}
ptr -> prev -> next = NULL;
free(ptr);
printf("nnode deletedn");
}
}
void deletion_specified()
{
struct node *ptr, *temp;
int val;
printf("n Enter the data after which the node is to be deleted : ");
scanf("%d", &val);
ptr = head;
while(ptr -> data != val)
ptr = ptr -> next;
if(ptr -> next == NULL)
{
printf("nCan't deleten");
}
else if(ptr -> next -> next == NULL)
{
ptr ->next = NULL;
}
else
{
temp = ptr -> next;
ptr -> next = temp -> next;
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
temp -> next -> prev = ptr;
free(temp);
printf("nnode deletedn");
}
}
void display()
{
struct node *ptr;
printf("n printing values...n");
ptr = head;
while(ptr != NULL)
{
printf("%dn",ptr->data);
ptr=ptr->next;
}
}
void search()
{
struct node *ptr;
int item,i=0,flag;
ptr = head;
if(ptr == NULL)
{
printf("nEmpty Listn");
}
else
{
printf("nEnter item which you want to search?n");
scanf("%d",&item);
while (ptr!=NULL)
{
if(ptr->data == item)
{
printf("nitem found at location %d ",i+1);
flag=0;
break;
}
else
{
flag=1;
}
i++;
ptr = ptr -> next;
}
if(flag==1)
{
printf("nItem not foundn");
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
}
}
}
Output
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
Enter your choice?
8
printing values...
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
Enter your choice?
1
Enter Item value12
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
Node inserted
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
Enter your choice?
1
Enter Item value123
Node inserted
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
Enter your choice?
1
Enter Item value1234
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
Node inserted
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
Enter your choice?
8
printing values...
1234
123
12
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
Enter your choice?
2
Enter value89
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
node inserted
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
Enter your choice?
3
Enter the location1
Enter value12345
node inserted
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
Enter your choice?
8
printing values...
1234
123
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
12345
12
89
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
Enter your choice?
4
node deleted
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
Enter your choice?
5
node deleted
*********Main Menu*********
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
Enter your choice?
8
printing values...
123
12345
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
Enter your choice?
6
Enter the data after which the node is to be deleted : 123
*********Main Menu*********
Choose one option from the following list ...
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
Enter your choice?
8
printing values...
123
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
Enter your choice?
7
Enter item which you want to search?
123
item found at location 1
*********Main Menu*********
Choose one option from the following list ...
===============================================
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
Enter your choice?
6
Enter the data after which the node is to be deleted : 123
Can't delete
*********Main Menu*********
Choose one option from the following list ...
===============================================
1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit
Enter your choice?
9
Exited..
Circular Single Linked List:
It is just a single linked list in which the link field of the last node points back to the address of the
first node. A circular linked list has no beginning and no end. It is necessary to establish a special
pointer called start pointer always pointing to the first node of the list. Circular linked lists are
frequently used instead of ordinary linked list because many operations are much easier to
implement. In circular linked list no null pointers are used, hence all pointers contain valid address.
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
Creating a circular single Linked List with „n‟ number of nodes:
The basic operations in a circular single linked list are:
• Creation.
• Insertion.
• Deletion.
• Traversing.
Inserting a node at the beginning:
Inserting a node at the end:
Deleting a node at the beginning:
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
Deleting a node at the end:
Menu-driven program in C implementing all operations
on circular singly linked list
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head;
void beginsert ();
void lastinsert ();
void randominsert();
void begin_delete();
void last_delete();
void random_delete();
void display();
void search();
void main ()
{
int choice =0;
while(choice != 7)
{
printf("n*********Main Menu*********n");
printf("nChoose one option from the following list ...n");
printf("n===============================================n");
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
printf("n1.Insert in beginingn2.Insert at lastn3.Delete from Beginningn4.Delete from
lastn5.Search for an elementn6.Shown7.Exitn");
printf("nEnter your choice?n");
scanf("n%d",&choice);
switch(choice)
{
case 1:
beginsert();
break;
case 2:
lastinsert();
break;
case 3:
begin_delete();
break;
case 4:
last_delete();
break;
case 5:
search();
break;
case 6:
display();
break;
case 7:
exit(0);
break;
default:
printf("Please enter valid choice..");
}
}
}
void beginsert()
{
struct node *ptr,*temp;
int item;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("nOVERFLOW");
}
else
{
printf("nEnter the node data?");
scanf("%d",&item);
ptr -> data = item;
if(head == NULL)
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
{
head = ptr;
ptr -> next = head;
}
else
{
temp = head;
while(temp->next != head)
temp = temp->next;
ptr->next = head;
temp -> next = ptr;
head = ptr;
}
printf("nnode insertedn");
}
}
void lastinsert()
{
struct node *ptr,*temp;
int item;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("nOVERFLOWn");
}
else
{
printf("nEnter Data?");
scanf("%d",&item);
ptr->data = item;
if(head == NULL)
{
head = ptr;
ptr -> next = head;
}
else
{
temp = head;
while(temp -> next != head)
{
temp = temp -> next;
}
temp -> next = ptr;
ptr -> next = head;
}
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
printf("nnode insertedn");
}
}
void begin_delete()
{
struct node *ptr;
if(head == NULL)
{
printf("nUNDERFLOW");
}
else if(head->next == head)
{
head = NULL;
free(head);
printf("nnode deletedn");
}
else
{ ptr = head;
while(ptr -> next != head)
ptr = ptr -> next;
ptr->next = head->next;
free(head);
head = ptr->next;
printf("nnode deletedn");
}
}
void last_delete()
{
struct node *ptr, *preptr;
if(head==NULL)
{
printf("nUNDERFLOW");
}
else if (head ->next == head)
{
head = NULL;
free(head);
printf("nnode deletedn");
}
else
{
ptr = head;
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
while(ptr ->next != head)
{
preptr=ptr;
ptr = ptr->next;
}
preptr->next = ptr -> next;
free(ptr);
printf("nnode deletedn");
}
}
void search()
{
struct node *ptr;
int item,i=0,flag=1;
ptr = head;
if(ptr == NULL)
{
printf("nEmpty Listn");
}
else
{
printf("nEnter item which you want to search?n");
scanf("%d",&item);
if(head ->data == item)
{
printf("item found at location %d",i+1);
flag=0;
}
else
{
while (ptr->next != head)
{
if(ptr->data == item)
{
printf("item found at location %d ",i+1);
flag=0;
break;
}
else
{
flag=1;
}
i++;
ptr = ptr -> next;
}
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
}
if(flag != 0)
{
printf("Item not foundn");
}
}
}
void display()
{
struct node *ptr;
ptr=head;
if(head == NULL)
{
printf("nnothing to print");
}
else
{
printf("n printing values ... n");
while(ptr -> next != head)
{
printf("%dn", ptr -> data);
ptr = ptr -> next;
}
printf("%dn", ptr -> data);
}
}
Circular Double Linked List:
A circular double linked list has both successor pointer and predecessor pointer in circular manner.
The objective behind considering circular double linked list is to simplify the insertion and deletion
operations performed on double linked list. In circular double linked list the right link of the right
most node points back to the start node and left link of the first node points to the last node.
A circular double linked list is shown in figure
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
Creating a Circular Double Linked List with „n‟ number of nodes
The basic operations in a circular double linked list are:
• Creation.
• Insertion.
• Deletion.
• Traversing.
Inserting a node at the beginning:
Inserting a node at the end:
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
Inserting a node at an intermediate position:
Deleting a node at the beginning:
Deleting a node at the end:
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
Deleting a node at Intermediate position:
C program to implement all the operations on circular doubly linked list
#include<stdio.h>
#include<stdlib.h>
struct node
{
struct node *prev;
struct node *next;
int data;
};
struct node *head;
void insertion_beginning();
void insertion_last();
void deletion_beginning();
void deletion_last();
void display();
void search();
void main ()
{
int choice =0;
while(choice != 9)
{
printf("n*********Main Menu*********n");
printf("nChoose one option from the following list ...n");
printf("n===============================================n");
printf("n1.Insert in Beginningn2.Insert at lastn3.Delete from Beginningn4.Delete from
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
lastn5.Searchn6.Shown7.Exitn");
printf("nEnter your choice?n");
scanf("n%d",&choice);
switch(choice)
{
case 1:
insertion_beginning();
break;
case 2:
insertion_last();
break;
case 3:
deletion_beginning();
break;
case 4:
deletion_last();
break;
case 5:
search();
break;
case 6:
display();
break;
case 7:
exit(0);
break;
default:
printf("Please enter valid choice..");
}
}
}
void insertion_beginning()
{
struct node *ptr,*temp;
int item;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("nOVERFLOW");
}
else
{
printf("nEnter Item value");
scanf("%d",&item);
ptr->data=item;
if(head==NULL)
{
head = ptr;
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
ptr -> next = head;
ptr -> prev = head;
}
else
{
temp = head;
while(temp -> next != head)
{
temp = temp -> next;
}
temp -> next = ptr;
ptr -> prev = temp;
head -> prev = ptr;
ptr -> next = head;
head = ptr;
}
printf("nNode insertedn");
}
}
void insertion_last()
{
struct node *ptr,*temp;
int item;
ptr = (struct node *) malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("nOVERFLOW");
}
else
{
printf("nEnter value");
scanf("%d",&item);
ptr->data=item;
if(head == NULL)
{
head = ptr;
ptr -> next = head;
ptr -> prev = head;
}
else
{
temp = head;
while(temp->next !=head)
{
temp = temp->next;
}
temp->next = ptr;
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
ptr ->prev=temp;
head -> prev = ptr;
ptr -> next = head;
}
}
printf("nnode insertedn");
}
void deletion_beginning()
{
struct node *temp;
if(head == NULL)
{
printf("n UNDERFLOW");
}
else if(head->next == head)
{
head = NULL;
free(head);
printf("nnode deletedn");
}
else
{
temp = head;
while(temp -> next != head)
{
temp = temp -> next;
}
temp -> next = head -> next;
head -> next -> prev = temp;
free(head);
head = temp -> next;
}
}
void deletion_last()
{
struct node *ptr;
if(head == NULL)
{
printf("n UNDERFLOW");
}
else if(head->next == head)
{
head = NULL;
free(head);
printf("nnode deletedn");
}
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
else
{
ptr = head;
if(ptr->next != head)
{
ptr = ptr -> next;
}
ptr -> prev -> next = head;
head -> prev = ptr -> prev;
free(ptr);
printf("nnode deletedn");
}
}
void display()
{
struct node *ptr;
ptr=head;
if(head == NULL)
{
printf("nnothing to print");
}
else
{
printf("n printing values ... n");
while(ptr -> next != head)
{
printf("%dn", ptr -> data);
ptr = ptr -> next;
}
printf("%dn", ptr -> data);
}
}
void search()
{
struct node *ptr;
int item,i=0,flag=1;
ptr = head;
if(ptr == NULL)
{
printf("nEmpty Listn");
}
else
{
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
printf("nEnter item which you want to search?n");
scanf("%d",&item);
if(head ->data == item)
{
printf("item found at location %d",i+1);
flag=0;
}
else
{
while (ptr->next != head)
{
if(ptr->data == item)
{
printf("item found at location %d ",i+1);
flag=0;
break;
}
else
{
flag=1;
}
i++;
ptr = ptr -> next;
}
}
if(flag != 0)
{
printf("Item not foundn");
}
}
}
Stacks Primitive Operations:
A stack is a container of objects that are inserted and removed according to the last-in first-out (LIFO)
principle. In the pushdown stacks only two operations are allowed: push the item into the stack, and pop
the item out of the stack. A stack is a limited access data structure - elements can be added and removed
from the stack only at the top. Push adds an item to the top of the stack, pop removes the item from the
top. A helpful analogy is to think of a stack of books; you can remove only the top book, also you can
add a new book on the top.
A stack may be implemented to have a bounded capacity. If the stack is full and does not contain enough
space to accept an entity to be pushed, the stack is then considered to be in an overflow state. The pop
operation removes an item from the top of the stack. A pop either reveals previously concealed items or
results in an empty stack, but, if the stack is empty, it goes into underflow state, which means no items
are present in stack to be removed.
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
Stack (ADT) Data Structure:
Stack is an Abstract data structure (ADT) works on the principle Last In First Out (LIFO). The last
element add to the stack is the first element to be delete. Insertion and deletion can be takes place at one
end called TOP. It looks like one side closed tube.
● The add operation of the stack is called push operation
● The delete operation is called as pop operation.
● Push operation on a full stack causes stack overflow.
● Pop operation on an empty stack causes stack underflow.
● SP is a pointer, which is used to access the top element of the stack.
● If you push elements that are added at the top of the stack;
● In the same way when we pop the elements, the element at the top of the stack is deleted.
Operations of stack:
There are two operations applied on stack they are
1. push
2. pop.
While performing push & pop operations the following test must be conducted on the stack.
1) Stack is empty or not
2) Stack is full or not
Push:
Push operation is used to add new elements in to the stack. At the time of addition first check the stack
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
is full or not. If the stack is full it generates an error message "stack overflow".
Pop:
Pop operation is used to delete elements from the stack. At the time of deletion first check the stack is
empty or not. If the stack is empty it generates an error message "stack underflow".
Representation of a Stack using Arrays:
Let us consider a stack with 6 elements capacity. This is called as the size of the stack. The number of
elements to be added should not exceed the maximum size of the stack. If we attempt to add new element
beyond the maximum size, we will encounter a stack overflow condition. Similarly, you cannot remove
elements beyond the base of the stack. If such is the case, we will reach a stack underflow condition.
When a element is added to a stack, the operation is performed by push().
When an element is taken off from the stack, the operation is performed by pop().
Source code for stack operations, using array:
STACK: Stack is a linear data structure which works under the principle of last in first out. Basic
operations: push, pop, display.
1. PUSH: if (top==MAX), display Stack overflow else reading the data and making stack [top]
=data and incrementing the top value by doing top++.
2. POP: if (top==0), display Stack underflow else printing the element at the top of the stack and
decrementing the top value by doing the top.
3. DISPLAY: IF (TOP==0), display Stack is empty else printing the elements in the stack from stack [0]
to stack [top].
Example:
#include <stdio.h>
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
int stack[100],i,j,choice=0,n,top=-1;
void push();
void pop();
void show();
void main ()
{
printf("Enter the number of elements in the stack ");
scanf("%d",&n);
printf("*********Stack operations using array*********");
printf("n----------------------------------------------n");
while(choice != 4)
{
printf("Chose one from the below options...n");
printf("n1.Pushn2.Popn3.Shown4.Exit");
printf("n Enter your choice n");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
show();
break;
}
case 4:
{
printf("Exiting....");
break;
}
default:
{
printf("Please Enter valid choice ");
}
};
}
}
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
void push ()
{
int val;
if (top == n )
printf("n Overflow");
else
{
printf("Enter the value?");
scanf("%d",&val);
top = top +1;
stack[top] = val;
}
}
void pop ()
{
if(top == -1)
printf("Underflow");
else
top = top -1;
}
void show()
{
for (i=top;i>=0;i--)
{
printf("%dn",stack[i]);
}
if(top == -1)
{
printf("Stack is empty");
}
}
Linked List Implementation of Stacks
The first implementation of a stack uses a singly linked list. We perform a push by inserting
at the front of the list. We perform a pop by deleting the element at the front of the list. A top operation
merely examines the element at the front of the list, returning its value. Sometimes the pop and top
operations are combined into one.
Creating an empty stack is also simple. We merely create a header node; make_null sets the
next pointer to NULL.
The push is implemented as an insertion into the front of a linked list, where the front of the
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
list serves as the top of the stack.
The top is performed by examining the element in the first position of the list. The
pop will delete from the front of the list.
It should be clear that all the operations take constant time, because less a loop that depends
on this size.
Drawbacks and solution
These implementations uses the calls to malloc and free are expensive, especially in
comparison to the pointer manipulation routines. Some of this can be avoided by using a second
stack, which is initially empty. When a cell is to be disposed from the first stack, it is merely placed
on the second stack. Then, when new cells are needed for the first stack, the second stack is checked
first.
Type declaration for linked list implementation of the stack ADT
struct Node;
typedef struct node *ptrToNode;
typedef ptrToNode Stack;
int IsEmpty(Stack S); Stack
CreateSatck(void);
void DisposeStack(Stack S);
void MakeEmpty(Stack S);
void Push(ElementType X, Stack S);
ElementType Top (Stack S);
Void Pop(Stack S);
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
struct node
{
Element_type element;
PtrToNode next;
};
Routine to test whether a stack is empty-linked list implementation
This routine checks whether Stack is empty or not. If it is not empty it will return a pointer
to the stack. Otherwise return NULL
int is_empty( STACK S )
{
return( S->next == NULL );
}
Routine to create an empty stack-linked list implementation
This routine creates a Stack and return a pointer of the stack. Otherwise return a warning to
say Stack is not created.
STACK create_stack( void )
{
STACK S;
S = malloc( sizeof( struct node ) ); if(
S == NULL )
fatal_error("Out of space!!!");
return S; }
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
Routine to make the stack as empty-linked list implementation
This routine makes Stack as empty and return NULL pointer.
Void makeEmpty( STACK S )
{
if( S == NULL )
error ("Must use create_stack first");
else
while (!IsEmpty(S))
pop(S); }
Routine to push onto a stack-linked list implementation
This routine is to insert the new element onto the top of the stack. Void
push( element_type x, STACK S )
{
node_ptr tmp_cell;
tmp_cell = (node_ptr) malloc( sizeof ( struct node ) ); if(
tmp_cell == NULL )
fatal_error("Out of space!!!");
else
{
tmp_cell->element = x;
tmp_cell->next = S->next;
S->next = tmp_cell; } }
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
Routine to return top element in a stack--linked list implementation
This routine is to return the topmost element from the stack.
element_type top( STACK S )
{
if( is_empty( S ) )
error("Empty stack");
else
return S->next->element;
}
Routine to pop from a stack--linked list implementation
This routine is to delete the topmost element from the stack.
Void pop( STACK S )
{
PtrToNode first_cell;
if( is_empty( S ) )
error("Empty stack");
else
{
first_cell = S->next;
S->next = S->next->next;
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
free( first_cell );
} }
Stack Applications
Stack is used for the following applications.
1. Reversing of the string
2. Tower’s of Hanoi’s problem
3. Balancing Symbols
4. Conversion of Infix to postfix expression
5. Conversion of Infix to prefix expression
6. Evaluation of Postfix expression
7. Used in Function calls
Balancing Symbols
Compilers check your programs for syntax errors, but frequently a lack of one symbol
(such as a missing brace or comment starter) will cause the compiler to
spill out a hundred lines of diagnostics without identifying the real error.
A useful tool in this situation is a program that checks whether everything is balanced.
Thus, every right brace, bracket, and parenthesis must correspond to
their left counterparts.
The sequence [()] is legal, but [(]) is wrong. That it is easy to check these things. For simplicity,
we will just check for balancing of parentheses, brackets, and braces and ignore any other character
that appears.
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
The simple algorithm uses a stack and is as follows:
● Make an empty stack.
● Read characters until end of file.
● If the character is an open anything, push it onto the stack.
● If it is a close anything, then
✔ If the stack is empty report an error.
✔ Otherwise, pop the stack.
✔ If the symbol popped is not the corresponding opening symbol, then report an error.
● At end of file, if the stack is not empty report an error.
Expression:
Expression is defined as a collection of operands and operators. The operators can be arithmetic,
logical or Boolean operators.
Rules for expression
✔ No two operand should be continuous
✔ No two operator should be continuous
Types of expression:
Based on the position of the operator, it is classified into three.
1. Infix Expression / Standard notation
2. Prefix Expression/ Polished notation
3. Postfix Expression / Reversed Polished notation
Infix Expression:
In an expression if the operator is placed in between the operands, then it is called as
Infix Expression.
Eg : A+B
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
Prefix Expression:
In an expression if the operator is placed before the operands, then it is called as Prefix
Expression.
Eg : +AB
Postfix Expression:
In an expression if the operator is placed after the operands, then it is called as Postfix
Expression.
Eg : AB+
Conversion of infix to Postfix Expressions
Stack is used to convert an expression in standard form (otherwise known as infix) into
postfix. We will concentrate on a small version of the general problem by allowing only the operators
+, *, and (, ), and insisting on the usual precedence rules.
Suppose we want to convert the infix expression
a + b * c + ( d * e + f ) * g .
A correct answer is a b c * + d e * f + g * +.
Algorithm:
1. We start with an initially empty stack
2. When an operand is read, it is immediately placed onto the output.
3. Operators are not immediately placed onto the output, so they must be saved somewhere. The
correct thing to do is to place operators that have been seen, but not placed on the output,
onto the stack. We will also stack left parentheses when they are encountered.
4. If we see a right parenthesis, then we pop the stack, writing symbols until we encounter a
(corresponding) left parenthesis, which is popped but not output.
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
5. If we see any other symbol ('+','*', '(' ), then we pop entries from the stack until we find an
entry of lower priority. One exception is that we never remove a '(' from the stack except
when processing a ')'. For the purposes of this operation, '+' has lowest priority and '(' highest.
When the popping is done, we push the operand onto the stack.
6. Finally, if we read the end of input, we pop the stack until it is empty, writing symbols onto
the output.
To see how this algorithm performs, we will convert the infix expression into its postfix
form.
a + b * c + (d * e + f) * g
First, the symbol a is read, so it is passed through to the output. Then '+' is read and pushed onto
the stack. Next b is read and passed through to the output. Then the stack will be as follows.
Next a '*' is read. The top entry on the operator stack has lower precedence than '*', so nothing is
output and '*' is put on the stack. Next, c is read and output.
The next symbol is a '+'. Checking the stack, we find that we will pop a '*' and place it on the output,
pop the other '+', which is not of lower but equal priority, on the stack, and then push the '+'.
The next symbol read is an '(', which, being of highest precedence, is placed on the stack. Then d is
read and output.
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
We continue by reading a '*'. Since open parentheses do not get removed except when a closed
parenthesis is being processed, there is no output. Next, e is read and output.
The next symbol read is a '+'. We pop and output '*' and then push '+'. Then we read and output f.
.
Now we read a ')', so the stack is emptied back to the '('. We output a '+' 0nto the stack.
We read a '*' next; it is pushed onto the stack. Then g is read and output.
The input is now empty, so we pop and output symbols from the stack until it is empty.
As before, this conversion requires only O(n) time and works in one pass through the input.
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
We can add subtraction and division to this repertoire by assigning subtraction and addition equal
priority and multiplication and division equal priority.
A subtle point is that the expression a - b - c will be converted to ab - c- and not abc - -. Our
algorithm does the right thing, because these operators associate from left to right. This is not
necessarily the case in general, since exponentiation associates right to left: 223 = 28 = 256 not 43 =
64.
Evaluation of a Postfix Expression
Algorithm:
When a number is seen, it is pushed onto the stack;
When an operator is seen, the operator is applied to the two numbers (symbols) that are popped
from the stackand the result is pushed onto the stack.
For example, the postfix expression 6 5 2 3 + 8 * + 3 + * is evaluated as follows: The
first four symbols are placed on the stack. The resulting stack is
TopofStack 3
2
5
6
Next a '+' is read, so 3 and 2 are popped from the stack and their sum, 5, is pushed.
TopofStack 5
5
6
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
Next 8 is pushed.
TopofStack 8
5
5
6
Now a '*' is seen, so 8 and 5 are popped as 8 * 5 = 40 is pushed.
TopofStack 40
5
6
Next a '+' is seen, so 40 and 5 are popped and 40 + 5 = 45 is pushed.
TopofStack 45
6
Now, 3 is pushed.
TopofStack 3
45
6
Next '+' pops 3 and 45 and pushes 45 + 3 = 48.
TopofStack 48
6
Finally, a '*' is seen and 48 and 6 are popped, the result 6 * 48 = 288 is pushed.
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
TopofStack 288
The time to evaluate a postfix expression is O(n), because processing each element in the
input consists of stack operations and thus takes constant time. The algorithm to do so is very simple.
Advantage of postfix expression:
When an expression is given in postfix notation, there is no need to know any precedence
rules;
Menu Driven program in C implementing all the stack operations using linked list :
#include <stdio.h>
#include <stdlib.h>
void push();
void pop();
void display();
struct node
{
int val;
struct node *next;
};
struct node *head;
void main ()
{
int choice=0;
printf("n*********Stack operations using linked list*********n");
printf("n----------------------------------------------n");
while(choice != 4)
{
printf("nnChose one from the below options...n");
printf("n1.Pushn2.Popn3.Shown4.Exit");
printf("n Enter your choice n");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
break;
}
case 3:
{
display();
break;
}
case 4:
{
printf("Exiting....");
break;
}
default:
{
printf("Please Enter valid choice ");
}
};
}
}
void push ()
{
int val;
struct node *ptr = (struct node*)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("not able to push the element");
}
else
{
printf("Enter the value");
scanf("%d",&val);
if(head==NULL)
{
ptr->val = val;
ptr -> next = NULL;
head=ptr;
}
else
{
ptr->val = val;
ptr->next = head;
head=ptr;
}
printf("Item pushed");
}
}
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
void pop()
{
int item;
struct node *ptr;
if (head == NULL)
{
printf("Underflow");
}
else
{
item = head->val;
ptr = head;
head = head->next;
free(ptr);
printf("Item popped");
}
}
void display()
{
int i;
struct node *ptr;
ptr=head;
if(ptr == NULL)
{
printf("Stack is emptyn");
}
else
{
printf("Printing Stack elements n");
while(ptr!=NULL)
{
printf("%dn",ptr->val);
ptr = ptr->next;
}
}
}
The Queue ADT
Queue is also a list in which insertion is done at one end, whereas deletion is performed at the other
end. Insertion will be at rear end of the queue and deletion will be at front of the queue. It is also
called as FIFO (First In First Out) which means the element which inserted first will be removed
first from the queue.
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
Queue Model
The basic operations on a queue are
1. enqueue, which inserts an element at the end of the list (called the rear)
2. dequeue, which deletes (and returns) the element at the start of the list (known as
the front).
Abstract model of a queue
Array Implementation of Queues
● Like stacks, both the linked list and array implementations give fast O(1) running times for
every operation. The linked list implementation is straightforward and left as an exercise. We
will now discuss an array implementation of queues.
● For each queue data structure, we keep an array, QUEUE[], and the positions q_front and
q_rear, which represent the ends of the queue. We also keep track of the number of elements
that are actually in the queue, q_size.
The following figure shows a queue in some intermediate state.
● By the way, the cells that are blanks have undefined values in them. In particular, the first
two cells have elements that used to be in the queue.
● To enqueue an element x, we increment q_size and q_rear, then set QUEUE[q_rear] = x.
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
● To dequeue an element, we set the return value to QUEUE[q_front], decrement
q_size, and then increment q_front.. After 10 enqueues, the queue appears to be full, since
q_front is now 10, and the next enqueue would be in a nonexistent position.
● However, there might only be a few elements in the queue, because several elements may
have already been dequeued.
● The simple solution is that whenever q_front or q_rear gets to the end of the array, it is
wrapped around to the beginning. This is known as a circular array implementation.
If incrementing either q_rear or q_front causes it to go past the array, the value is reset to the first
position in the array.
There are two warnings about the circular array implementation of queues.
● First, it is important to check the queue for emptiness, because a dequeue when the queue is
empty will return an undefined value.
● Secondly, some programmers use different ways of representing the front and rear of a queue.
For instance, some do not use an entry to keep track of the size, because they rely on the base
case that when the queue is empty, q_rear = q_front - 1.
If the size is not part of the structure, then if the array size is A_SIZE, the queue is full when there
are A_SIZE -1 elements.
In applications where you are sure that the number of enqueues is not larger than the size
of the queue, the wraparound is not necessary.
The routine queue_create and queue_dispose routines also need to be provided. We also
provide routines to test whether a queue is empty and to make an empty queue.
Notice that q_rear is preinitialized to 1 before q_front. The final operation we will write is
the enqueue routine.
Type declarations for queue--array implementation
struct QueueRecord
{
int Capacity;
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
int Front; int
Rear;
int Size; /* Current # of elements in Q */
ElementType *Array;
};
typedef struct QueueRecord * Queue;
Routine to test whether a queue is empty-array implementation
int isempty( Queue Q )
{
return( Q->q_size == 0 );
}
Routine to make an empty queue-array implementation
Void makeempty ( Queue Q )
{
Q->size = 0;
Q->Front = -1;
Q->Rear = -1;
}
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
Routines to enqueue-array implementation
static int succ(int value, Queue Q )
{
if( ++value = = Q->Capacity )
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
value = 0; return
value; }
Void enqueue( Elementtype x, Queue Q )
{
if( isfull( Q ) )
error("Full queue");
else
{
Q->Size++;
Q->Rear = succ( Q->Rear, Q ); Q-
>Array[ Q->Rear ] = x;
} }
Applications of Queues
The applications are,
1. When jobs are submitted to a printer, they are arranged in order of arrival. Then jobs sent to
a line printer are placed on a queue.
2. Lines at ticket counters are queues, because service is first-come first-served.
3. Another example concerns computer networks. There are many network setups of personal
computers in which the disk is attached to one machine, known as the file server.
4. Users on other machines are given access to files on a first-come first-served basis, so the
data structure is a queue.
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II
Circular Queue:
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II NOTES
82
In Circular Queue, the insertion of a new element is performed at the very first locations of the
queue if the last location of the queue is full, in which the first element comes after the last
element.
Advantages:
It overcomes the problem of unutilized space in linear queue, when it is implemented as arrays.
To perform the insertion of the element to the queue, the position of the element is calculated as
rear= (rear+1) % queue_size and set Q[rear]=value.
Similarly the element deleted from the queue using front = (front + 1) % queue_size.
Enqueue:
This routine insert the new element at rear position of the circular queue.
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II NOTES
83
Dequeue:
This routine deletes the element from the front of the circular queue. void
CQ_dequeue( )
{
If(front==-1 && rear==-1)
Print(“Queue is empty”); Else
{
Temp=CQueue[front];
If(front==rear) Front=rear=-
1;
Else
Front=(front+1)% maxsize;
} }
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II NOTES
84
Priority queue
A priority queue is an abstract data type that behaves similarly to the normal queue except that each element
has some priority, i.e., the element with the highest priority would come first in a priority queue. The priority
of the elements in a priority queue will determine the order in which elements are removed from the priority
queue.
The priority queue supports only comparable elements, which means that the elements are either arranged in an
ascending or descending order.
For example, suppose we have some values like 1, 3, 4, 8, 14, 22 inserted in a priority queue with an ordering
imposed on the values is from least to the greatest. Therefore, the 1 number would be having the highest
priority while 22 will be having the lowest priority.
Characteristics of a Priority queue
A priority queue is an extension of a queue that contains the following characteristics:
o Every element in a priority queue has some priority associated with it.
o An element with the higher priority will be deleted before the deletion of the lesser priority.
o If two elements in a priority queue have the same priority, they will be arranged using the FIFO
principle.
Types of Priority Queue
There are two types of priority queue:
o Ascending order priority queue: In ascending order priority queue, a lower priority number is given as a
higher priority in a priority. For example, we take the numbers from 1 to 5 arranged in an ascending order
like 1,2,3,4,5; therefore, the smallest number, i.e., 1 is given as the highest priority in a priority queue.
o Descending order priority queue: In descending order priority queue, a higher priority number is given
as a higher priority in a priority. For example, we take the numbers from 1 to 5 arranged in descending
order like 5, 4, 3, 2, 1; therefore, the largest number, i.e., 5 is given as the highest priority in a priority
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II NOTES
85
queue.
Representation of priority queue
Now, we will see how to represent the priority queue through a one-way list.
We will create the priority queue by using the list given below in which INFO list contains the data
elements, PRN list contains the priority numbers of each data element available in the INFO list, and LINK
basically contains the address of the next node.
Priority Queue Operations
The common operations that we can perform on a priority queue are insertion, deletion and peek. Let's see how
we can maintain the heap data structure.
o Inserting the element in a priority queue (max heap)
If we insert an element in a priority queue, it will move to the empty slot by looking from top to bottom and left to
right.
If the element is not in a correct place then it is compared with the parent node; if it is found out of order,
elements are swapped. This process continues until the element is placed in a correct position.
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II NOTES
86
o Removing the minimum element from the priority queue
As we know that in a max heap, the maximum element is the root node. When we remove the root node, it creates
an empty slot. The last inserted element will be added in this empty slot. Then, this element is compared with the
child nodes, i.e., left-child and right child, and swap with the smaller of the two. It keeps moving down the tree
until the heap property is restored.
Applications of Priority queue
The following are the applications of the priority queue:
o It is used in the Dijkstra's shortest path algorithm.
o It is used in prim's algorithm
o It is used in data compression techniques like Huffman code.
o It is used in heap sort.
o It is also used in operating system like priority scheduling, load balancing and interrupt handling.
Program to create the priority queue using the binary max heap.
#include <stdio.h>
#include <stdio.h>
int heap[40];
int size=-1;
// retrieving the parent node of the child node
int parent(int i)
{
return (i - 1) / 2;
}
// retrieving the left child of the parent node.
int left_child(int i)
{
return i+1;
}
// retrieving the right child of the parent
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II NOTES
87
int right_child(int i)
{
return i+2;
}
// Returning the element having the highest priority
int get_Max()
{
return heap[0];
}
//Returning the element having the minimum priority
int get_Min()
{
return heap[size];
}
// function to move the node up the tree in order to restore the heap property.
void moveUp(int i)
{
while (i > 0)
{
// swapping parent node with a child node
if(heap[parent(i)] < heap[i]) {
int temp;
temp=heap[parent(i)];
heap[parent(i)]=heap[i];
heap[i]=temp;
}
// updating the value of i to i/2
i=i/2;
}
}
//function to move the node down the tree in order to restore the heap property.
void moveDown(int k)
{
int index = k;
// getting the location of the Left Child
int left = left_child(k);
if (left <= size && heap[left] > heap[index]) {
index = left;
}
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II NOTES
88
// getting the location of the Right Child
int right = right_child(k);
if (right <= size && heap[right] > heap[index]) {
index = right;
}
// If k is not equal to index
if (k != index) {
int temp;
temp=heap[index];
heap[index]=heap[k];
heap[k]=temp;
moveDown(index);
}
}
// Removing the element of maximum priority
void removeMax()
{
int r= heap[0];
heap[0]=heap[size];
size=size-1;
moveDown(0);
}
//inserting the element in a priority queue
void insert(int p)
{
size = size + 1;
heap[size] = p;
// move Up to maintain heap property
moveUp(size);
}
//Removing the element from the priority queue at a given index i.
void delete(int i)
{
heap[i] = heap[0] + 1;
// move the node stored at ith location is shifted to the root node
moveUp(i);
// Removing the node having maximum priority
removeMax();
}
191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II NOTES
89
int main()
{
// Inserting the elements in a priority queue
insert(20);
insert(19);
insert(21);
insert(18);
insert(12);
insert(17);
insert(15);
insert(16);
insert(14);
int i=0;
printf("Elements in a priority queue are : ");
for(int i=0;i<=size;i++)
{
printf("%d ",heap[i]);
}
delete(2); // deleting the element whose index is 2.
printf("nElements in a priority queue after deleting the element are : ");
for(int i=0;i<=size;i++)
{
printf("%d ",heap[i]);
}
int max=get_Max();
printf("nThe element which is having the highest priority is %d: ",max);
int min=get_Min();
printf("nThe element which is having the minimum priority is : %d",min);
return 0;
}

Contenu connexe

Similaire à UNIT II.docx

Chapter 1 Introduction to Data Structures and Algorithms.pdf
Chapter 1 Introduction to Data Structures and Algorithms.pdfChapter 1 Introduction to Data Structures and Algorithms.pdf
Chapter 1 Introduction to Data Structures and Algorithms.pdfAxmedcarb
 
Iare ds lecture_notes_2
Iare ds lecture_notes_2Iare ds lecture_notes_2
Iare ds lecture_notes_2RajSingh734307
 
Introduction to data structures (ss)
Introduction to data structures (ss)Introduction to data structures (ss)
Introduction to data structures (ss)Madishetty Prathibha
 
Unit i data structure FYCS MUMBAI UNIVERSITY SEM II
Unit i  data structure FYCS MUMBAI UNIVERSITY SEM II Unit i  data structure FYCS MUMBAI UNIVERSITY SEM II
Unit i data structure FYCS MUMBAI UNIVERSITY SEM II ajay pashankar
 
Data Structures & Recursion-Introduction.pdf
Data Structures & Recursion-Introduction.pdfData Structures & Recursion-Introduction.pdf
Data Structures & Recursion-Introduction.pdfMaryJacob24
 
DS-UNIT 1 FINAL (2).pptx
DS-UNIT 1 FINAL (2).pptxDS-UNIT 1 FINAL (2).pptx
DS-UNIT 1 FINAL (2).pptxprakashvs7
 
Data Structures_Introduction
Data Structures_IntroductionData Structures_Introduction
Data Structures_IntroductionThenmozhiK5
 
Unit 1-Introduction to Data Structures-BCA.pdf
Unit 1-Introduction to Data Structures-BCA.pdfUnit 1-Introduction to Data Structures-BCA.pdf
Unit 1-Introduction to Data Structures-BCA.pdfMaryJacob24
 
DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS Adams Sidibe
 
DataStructurePpt.pptx
DataStructurePpt.pptxDataStructurePpt.pptx
DataStructurePpt.pptxssuser031f35
 
Chapter 1( intro &amp; overview)
Chapter 1( intro &amp; overview)Chapter 1( intro &amp; overview)
Chapter 1( intro &amp; overview)MUHAMMAD AAMIR
 
chapter 1 Introduction to Ds and Algorithm Anyasis.pptx
chapter 1 Introduction to Ds and Algorithm Anyasis.pptxchapter 1 Introduction to Ds and Algorithm Anyasis.pptx
chapter 1 Introduction to Ds and Algorithm Anyasis.pptxAmrutaNavale2
 
Lecture 1. Data Structure & Algorithm.pptx
Lecture 1. Data Structure & Algorithm.pptxLecture 1. Data Structure & Algorithm.pptx
Lecture 1. Data Structure & Algorithm.pptxArifKamal36
 
Lesson 1 - Data Structures and Algorithms Overview.pdf
Lesson 1 - Data Structures and Algorithms Overview.pdfLesson 1 - Data Structures and Algorithms Overview.pdf
Lesson 1 - Data Structures and Algorithms Overview.pdfLeandroJrErcia
 
Introduction to data structure
Introduction to data structureIntroduction to data structure
Introduction to data structureadeel hamid
 
DS Module 1.pptx
DS Module 1.pptxDS Module 1.pptx
DS Module 1.pptxSaralaT3
 
DS Module 1.pptx
DS Module 1.pptxDS Module 1.pptx
DS Module 1.pptxsarala9
 

Similaire à UNIT II.docx (20)

Chapter 1 Introduction to Data Structures and Algorithms.pdf
Chapter 1 Introduction to Data Structures and Algorithms.pdfChapter 1 Introduction to Data Structures and Algorithms.pdf
Chapter 1 Introduction to Data Structures and Algorithms.pdf
 
Iare ds lecture_notes_2
Iare ds lecture_notes_2Iare ds lecture_notes_2
Iare ds lecture_notes_2
 
Introduction to data structures (ss)
Introduction to data structures (ss)Introduction to data structures (ss)
Introduction to data structures (ss)
 
Unit i data structure FYCS MUMBAI UNIVERSITY SEM II
Unit i  data structure FYCS MUMBAI UNIVERSITY SEM II Unit i  data structure FYCS MUMBAI UNIVERSITY SEM II
Unit i data structure FYCS MUMBAI UNIVERSITY SEM II
 
Data Structures & Recursion-Introduction.pdf
Data Structures & Recursion-Introduction.pdfData Structures & Recursion-Introduction.pdf
Data Structures & Recursion-Introduction.pdf
 
DS-UNIT 1 FINAL (2).pptx
DS-UNIT 1 FINAL (2).pptxDS-UNIT 1 FINAL (2).pptx
DS-UNIT 1 FINAL (2).pptx
 
Data Structures_Introduction
Data Structures_IntroductionData Structures_Introduction
Data Structures_Introduction
 
Lect 1-2 Zaheer Abbas
Lect 1-2 Zaheer AbbasLect 1-2 Zaheer Abbas
Lect 1-2 Zaheer Abbas
 
Unit 1-Introduction to Data Structures-BCA.pdf
Unit 1-Introduction to Data Structures-BCA.pdfUnit 1-Introduction to Data Structures-BCA.pdf
Unit 1-Introduction to Data Structures-BCA.pdf
 
Lect 1-2
Lect 1-2Lect 1-2
Lect 1-2
 
DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS
 
DataStructurePpt.pptx
DataStructurePpt.pptxDataStructurePpt.pptx
DataStructurePpt.pptx
 
Chapter 1( intro &amp; overview)
Chapter 1( intro &amp; overview)Chapter 1( intro &amp; overview)
Chapter 1( intro &amp; overview)
 
Lecture1 data structure(introduction)
Lecture1 data structure(introduction)Lecture1 data structure(introduction)
Lecture1 data structure(introduction)
 
chapter 1 Introduction to Ds and Algorithm Anyasis.pptx
chapter 1 Introduction to Ds and Algorithm Anyasis.pptxchapter 1 Introduction to Ds and Algorithm Anyasis.pptx
chapter 1 Introduction to Ds and Algorithm Anyasis.pptx
 
Lecture 1. Data Structure & Algorithm.pptx
Lecture 1. Data Structure & Algorithm.pptxLecture 1. Data Structure & Algorithm.pptx
Lecture 1. Data Structure & Algorithm.pptx
 
Lesson 1 - Data Structures and Algorithms Overview.pdf
Lesson 1 - Data Structures and Algorithms Overview.pdfLesson 1 - Data Structures and Algorithms Overview.pdf
Lesson 1 - Data Structures and Algorithms Overview.pdf
 
Introduction to data structure
Introduction to data structureIntroduction to data structure
Introduction to data structure
 
DS Module 1.pptx
DS Module 1.pptxDS Module 1.pptx
DS Module 1.pptx
 
DS Module 1.pptx
DS Module 1.pptxDS Module 1.pptx
DS Module 1.pptx
 

Plus de Revathiparamanathan (20)

UNIT 1 NOTES.docx
UNIT 1 NOTES.docxUNIT 1 NOTES.docx
UNIT 1 NOTES.docx
 
Unit 3,4.docx
Unit 3,4.docxUnit 3,4.docx
Unit 3,4.docx
 
UNIT V.docx
UNIT V.docxUNIT V.docx
UNIT V.docx
 
COMPILER DESIGN.docx
COMPILER DESIGN.docxCOMPILER DESIGN.docx
COMPILER DESIGN.docx
 
UNIT -III.docx
UNIT -III.docxUNIT -III.docx
UNIT -III.docx
 
UNIT -IV.docx
UNIT -IV.docxUNIT -IV.docx
UNIT -IV.docx
 
UNIT - II.docx
UNIT - II.docxUNIT - II.docx
UNIT - II.docx
 
UNIT -V.docx
UNIT -V.docxUNIT -V.docx
UNIT -V.docx
 
UNIT - I.docx
UNIT - I.docxUNIT - I.docx
UNIT - I.docx
 
CC -Unit3.pptx
CC -Unit3.pptxCC -Unit3.pptx
CC -Unit3.pptx
 
CC -Unit4.pptx
CC -Unit4.pptxCC -Unit4.pptx
CC -Unit4.pptx
 
CC.pptx
CC.pptxCC.pptx
CC.pptx
 
Unit 4 notes.pdf
Unit 4 notes.pdfUnit 4 notes.pdf
Unit 4 notes.pdf
 
Unit 3 notes.pdf
Unit 3 notes.pdfUnit 3 notes.pdf
Unit 3 notes.pdf
 
Unit 1 notes.pdf
Unit 1 notes.pdfUnit 1 notes.pdf
Unit 1 notes.pdf
 
Unit 2 notes.pdf
Unit 2 notes.pdfUnit 2 notes.pdf
Unit 2 notes.pdf
 
Unit 5 notes.pdf
Unit 5 notes.pdfUnit 5 notes.pdf
Unit 5 notes.pdf
 
CC.pptx
CC.pptxCC.pptx
CC.pptx
 
Unit-4 Day1.pptx
Unit-4 Day1.pptxUnit-4 Day1.pptx
Unit-4 Day1.pptx
 
Scala Introduction.pptx
Scala Introduction.pptxScala Introduction.pptx
Scala Introduction.pptx
 

Dernier

Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdfSuman Jyoti
 
Intro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfIntro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfrs7054576148
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringmulugeta48
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01KreezheaRecto
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfJiananWang21
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Standamitlee9823
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfRagavanV2
 

Dernier (20)

Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
Intro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfIntro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdf
 
chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Netaji Nagar, Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Koregaon Park  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Koregaon Park 6297143586 Call Hot Ind...
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 

UNIT II.docx

  • 1. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II UNIT II : LINEAR DATA STRUCTURES – LIST Abstract Data Types (ADTs) – List ADT – array-based implementation – linked list implementation ––singly linked lists- circularly linked lists- doubly-linked lists – Stack ADT- Queue ADT- applications of queues. Data Structure The data structure name indicates itself that organizing the data in memory. There are many ways of organizing the data in the memory as we have already seen one of the data structures, i.e., array in C language. Array is a collection of memory elements in which data is stored sequentially, i.e., one after another. In other words, we can say that array stores the elements in a continuous manner. This organization of data is done with the help of an array of data structures. There are also other ways to organize the data in memory. Let's see the different types of data structures. The data structure is not any programming language like C, C++, java, etc. It is a set of algorithms that we can use in any programming language to structure the data in the memory. To structure the data in memory, 'n' number of algorithms were proposed, and all these algorithms are known as Abstract data types. These abstract data types are the set of rules. Types of Data Structures There are two types of data structures: Primitive data structure Non-primitive data structure Primitive Data structure The primitive data structures are primitive data types. The int, char, float, double, and pointer are the primitive data structures that can hold a single value. Non-Primitive Data structure The non-primitive data structure is divided into two types: Linear data structure Non-linear data structure Linear Data Structure
  • 2. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II The arrangement of data in a sequential manner is known as a linear data structure. The data structures used for this purpose are Arrays, Linked list, Stacks, and Queues. In these data structures, one element is connected to only one another element in a linear form. When one element is connected to the 'n' number of elements known as a non-linear data structure. The best example is trees and graphs. In this case, the elements are arranged in a random manner. We will discuss the above data structures in brief in the coming topics. Now, we will see the common operations that we can perform on these data structures. Data structures can also be classified as: Static data structure: It is a type of data structure where the size is allocated at the compile time. Therefore, the maximum size is fixed. Dynamic data structure: It is a type of data structure where the size is allocated at the run time. Therefore, the maximum size is flexible. Major Operations The major or the common operations that can be performed on the data structures are: Searching: We can search for any element in a data structure. Sorting: We can sort the elements of a data structure either in an ascending or descending order. Insertion: We can also insert the new element in a data structure. Updation: We can also update the element, i.e., we can replace the element with another element. Deletion: We can also perform the delete operation to remove the element from the data structure. Which Data Structure? A data structure is a way of organizing the data so that it can be used efficiently. Here, we have used the word efficiently, which in terms of both the space and time. For example, a stack is an ADT (Abstract data type) which uses either arrays or linked list data structure for the implementation. Therefore, we conclude that we require some data structure to implement a particular ADT.
  • 3. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II An ADT tells what is to be done and data structure tells how it is to be done. In other words, we can say that ADT gives us the blueprint while data structure provides the implementation part. Now the question arises: how can one get to know which data structure to be used for a particular ADT?. As the different data structures can be implemented in a particular ADT, but the different implementations are compared for time and space. For example, the Stack ADT can be implemented by both Arrays and linked list. Suppose the array is providing time efficiency while the linked list is providing space efficiency, so the one which is the best suited for the current user's requirements will be selected. Advantages of Data structures The following are the advantages of a data structure: Efficiency: If the choice of a data structure for implementing a particular ADT is proper, it makes the program very efficient in terms of time and space. Reusability: he data structures provide reusability means that multiple client programs can use the data structure. Abstraction: The data structure specified by an ADT also provides the level of abstraction. The client cannot see the internal working of the data structure, so it does not have to worry about the implementation part. The client can only see the interface. Basic Terminology: Data structures are the building blocks of any program or the software. Choosing the appropriate data structure for a program is the most difficult task for a programmer. Following terminology is used as far as data structures are concerned Data: Data can be defined as an elementary value or the collection of values, for example, student's name and its id are the data about the student. Group Items: Data items which have subordinate data items are called Group item, for example, name of a student can have first name and the last name. Record: Record can be defined as the collection of various data items, for example, if we talk about the student entity, then its name, address, course and marks can be grouped together to form the record for the student. File: A File is a collection of various records of one type of entity, for example, if there are 60 employees in the class, then there will be 20 records in the related file where each record
  • 4. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II contains the data about each employee. Attribute and Entity: An entity represents the class of certain objects. it contains various attributes. Each attribute represents the particular property of that entity. Field: Field is a single elementary unit of information representing the attribute of an entity. Need of Data Structures As applications are getting complexed and amount of data is increasing day by day, there may arrise the following problems: Processor speed: To handle very large amout of data, high speed processing is required, but as the data is growing day by day to the billions of files per entity, processor may fail to deal with that much amount of data. Data Search: Consider an inventory size of 106 items in a store, If our application needs to search for a particular item, it needs to traverse 106 items every time, results in slowing down the search process. Multiple requests: If thousands of users are searching the data simultaneously on a web server, then there are the chances that a very large server can be failed during that process in order to solve the above problems, data structures are used. Data is organized to form a data structure in such a way that all items are not required to be searched and required data can be searched instantly. Advantages of Data Structures Efficiency: Efficiency of a program depends upon the choice of data structures. For example: suppose, we have some data and we need to perform the search for a perticular record. In that case, if we organize our data in an array, we will have to search sequentially element by element. hence, using array may not be very efficient here. There are better data structures which can make the search process efficient like ordered array, binary search tree or hash tables. Reusability: Data structures are reusable, i.e. once we have implemented a particular data structure, we can use it at any other place. Implementation of data structures can be compiled into libraries which can be used by different clients. Abstraction: Data structure is specified by the ADT which provides a level of abstraction. The client program uses the data structure through interface only, without getting into the implementation details.
  • 5. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II Data Structure Classification Linear Data Structures: A data structure is called linear if all of its elements are arranged in the linear order. In linear data structures, the elements are stored in non-hierarchical way where each element has the successors and predecessors except the first and last element. Types of Linear Data Structures are given below: Arrays: An array is a collection of similar type of data items and each data item is called an element of the array. The data type of the element may be any valid data type like char, int, float or double. The elements of array share the same variable name but each one carries a different index number known as subscript. The array can be one dimensional, two dimensional or multidimensional. The individual elements of the array age are: age[0], age[1], age[2], age[3],......... age[98], age[99]. Linked List: Linked list is a linear data structure which is used to maintain a list in the memory. It can be seen as the collection of nodes stored at non-contiguous memory locations. Each node of the list contains a pointer to its adjacent node. Stack: Stack is a linear list in which insertion and deletions are allowed only at one end, called top. A stack is an abstract data type (ADT), can be implemented in most of the programming
  • 6. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II languages. It is named as stack because it behaves like a real-world stack, for example: - piles of plates or deck of cards etc. Queue: Queue is a linear list in which elements can be inserted only at one end called rear and deleted only at the other end called front. It is an abstract data structure, similar to stack. Queue is opened at both end therefore it follows First-In-First-Out (FIFO) methodology for storing the data items. Non Linear Data Structures: This data structure does not form a sequence i.e. each item or element is connected with two or more other items in a non-linear arrangement. The data elements are not arranged in sequential structure. Types of Non Linear Data Structures are given below: Trees: Trees are multilevel data structures with a hierarchical relationship among its elements known as nodes. The bottommost nodes in the herierchy are called leaf node while the topmost node is called root node. Each node contains pointers to point adjacent nodes. Tree data structure is based on the parent-child relationship among the nodes. Each node in the tree can have more than one children except the leaf nodes whereas each node can have atmost one parent except the root node. Trees can be classfied into many categories which will be discussed later in this tutorial. Graphs: Graphs can be defined as the pictorial representation of the set of elements (represented by vertices) connected by the links known as edges. A graph is different from tree in the sense that a graph can have cycle while the tree can not have the one. Operations on data structure 1) Traversing: Every data structure contains the set of data elements. Traversing the data structure means visiting each element of the data structure in order to perform some specific operation like searching or sorting. Example: If we need to calculate the average of the marks obtained by a student in 6 different subject, we need to traverse the complete array of marks and calculate the total sum, then we will devide that sum by the number of subjects i.e. 6, in order to find the average. 2) Insertion: Insertion can be defined as the process of adding the elements to the data structure at any location. If the size of data structure is n then we can only insert n-1 data elements into it. 3) Deletion:The process of removing an element from the data structure is called Deletion.
  • 7. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II We can delete an element from the data structure at any random location. If we try to delete an element from an empty data structure then underflow occurs. 4) Searching: The process of finding the location of an element within the data structure is called Searching. There are two algorithms to perform searching, Linear Search and Binary Search. We will discuss each one of them later in this tutorial. 5) Sorting: The process of arranging the data structure in a specific order is known as Sorting. There are many algorithms that can be used to perform sorting, for example, insertion sort, selection sort, bubble sort, etc. 6) Merging: When two lists List A and List B of size M and N respectively, of similar type of elements, clubbed or joined to produce the third list, List C of size (M+N), then this process is called merging Abstract Data Types An abstract data type (ADT) is a set of operations. Abstract data types are mathematical abstractions; ADT's defines how the set of operations is implemented. This can be viewed as an extension of modular design. Objects such as lists, sets, and graphs, along with their operations, can be viewed as abstract data types, just as integers, reals, and booleans are data types. Use of ADT Reusability of the code, that the implementation of these operations is written once in the program, and any other part of the program that needs to perform an operation on the ADT can do so by calling the appropriate function. The List ADT A general list of the form a1, a2, a3, . . . , an. We say that the size of this list is n. We will call the special list of size 0 a null list. For any list except the null list, we say that ai+l follows (or succeeds) ai (i < n) and that ai-1 precedes ai (i > 1). The first element of the list is a1, and the last element is an. there is no predecessor of a1 or the successor of an. The position of element ai in a list is i.
  • 8. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II Some operations in list are, 1. Find, which returns the position of the first occurrence of a key; 2. Insert and delete, which generally insert and delete some key from some position in the list; 3. Find_kth, which returns the element in some position (specified as an argument). Example: 1. If the list is 34, 12, 52, 16, 12, then find(52) might return 3; 2. Insert(x,3) might make the list into 34, 12, 52, x, 16, 12 (if we insert after the position given); 3. Delete (3) might turn that list into 34, 12, x, 16, 12. Linked List Linked lists and arrays are similar since they both store collections of data. Array is the most common data structure used to store collections of elements. Arrays are convenient to declare and provide the easy syntax to access any element by its index number. Once the array is set up, access to any element is convenient and fast. The disadvantages of arrays are: • The size of the array is fixed. Most often this size is specified at compile time. This makes the programmers to allocate arrays, which seems "large enough" than required. • Inserting new elements at the front is potentially expensive because existing elements need to be shifted over to make room. • Deleting an element from an array is not possible. Linked lists have their own strengths and weaknesses, but they happen to be strong where arrays are weak. ● Generally array's allocates the memory for all its elements in one block whereas linked lists use an entirely different strategy. Linked lists allocate memory for each element separately and only when necessary. Linked List Concepts: A linked list is a non-sequential collection of data items. It is a dynamic data structure. For every data item in a linked list, there is an associated pointer that would give the memory location of the next data item in the linked list. The data items in the linked list are not in consecutive memory locations. They may be anywhere, but the accessing of these data items is easier as each data item contains the address of the next data item.
  • 9. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II Advantages of linked lists: Linked lists have many advantages. Some of the very important advantages are: 1. Linked lists are dynamic data structures. i.e., they can grow or shrink during the execution of a program. 2. Linked lists have efficient memory utilization. Here, memory is not preallocated. Memory is allocated whenever it is required and it is de-allocated (removed) when it is no longer needed. 3. Insertion and Deletions are easier and efficient. Linked lists provide flexibility in inserting a data item at a specified position and deletion of the data item from the given position. 4. Many complex applications can be easily carried out with linked lists. Disadvantages of linked lists: 1. It consumes more space because every node requires a additional pointer to store address of the next node. 2. Searching a particular element in list is difficult and also time consuming. Types of Linked Lists: Basically we can put linked lists into the following four items: 1. Single Linked List. 2. Double Linked List. 3. Circular Linked List. 4. Circular Double Linked List. A single linked list is one in which all nodes are linked together in some sequential manner. Hence, it is also called as linear linked list. A double linked list is one in which all nodes are linked together by multiple links which helps in accessing both the successor node (next node) and predecessor node (previous node) from any arbitrary node within the list. Therefore each node in a double linked list has two link fields (pointers) to point to the left node (previous) and the right node (next). This helps to traverse in forward direction and backward direction. A circular linked list is one, which has no beginning and no end. A single linked list can be made a circular linked list by simply storing address of the very first node in the link field of the last node.A circular double linked list is one, which has both the successor pointer and predecessor
  • 10. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II pointer in the circular manner. Applications of linked list: 1. Linked lists are used to represent and manipulate polynomial. Polynomials are expression containing terms with non zero coefficient and exponents. For example: P(x) = a0 Xn + a1 Xn-1 + …… + an-1 X + an 2. Represent very large numbers and operations of the large number such as addition, multiplication and division. 3. Linked lists are to implement stack, queue, trees and graphs. 4. Implement the symbol table in compiler construction. Single Linked List: A linked list allocates space for each element separately in its own block of memory called a "node". The list gets an overall structure by using pointers to connect all its nodes together like the links in a chain. Each node contains two fields; a "data" field to store whatever element, and a "next" field which is a pointer used to link to the next node. Each node is allocated in the heap using malloc(), so the node memory continues to exist until it is explicitly de-allocated using free(). The front of the list is a pointer to the “start” node.
  • 11. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II A single linked list The beginning of the linked list is stored in a "start" pointer which points to the first node. The first node contains a pointer to the second node. The second node contains a pointer to the third node, ... and so on. The last node in the list has its next field set to NULL to mark the end of the list. Code can access any node in the list by starting at the start and following the next pointers. The start pointer is an ordinary local pointer variable, so it is drawn separately on the left top to show that it is in the stack. The list nodes are drawn on the right to show that they are allocated in the heap. The basic operations in a single linked list are: • Creation. • Insertion. • Deletion. • Traversing. Creating a node for Single Linked List: Creating a singly linked list starts with creating a node. Sufficient memory has to be allocated for creating a node. The information is stored in the memory. Insertion of a Node: One of the most primitive operations that can be done in a singly linked list is the insertion of a node. Memory is to be allocated for the new node (in a similar way that is done while creating a list) before reading the data. The new node will contain empty data field and empty next field. The data field of the new node is then stored with the information read from the user. The next field of the new node is assigned to NULL. The new node can then be inserted at three different places
  • 12. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II namely: • Inserting a node at the beginning. • Inserting a node at the end. • Inserting a node at intermediate position. ● Inserting a node at the beginning. ● Inserting a node at the end: ● Inserting a node into the single linked list at a specified intermediate position other than beginning and end.
  • 13. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II Deletion of a node: Another primitive operation that can be done in a singly linked list is the deletion of a node. Memory is to be released for the node to be deleted. A node can be deleted from the list from three different places namely. • Deleting a node at the beginning. • Deleting a node at the end. • Deleting a node at intermediate position. Deleting a node at the beginning: Deleting a node at the end: Deleting a node at Intermediate position: The following steps are followed, to delete a node from an intermediate position in the list (List must contain more than two node).
  • 14. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II Traversal and displaying a list (Left to Right): To display the information, you have to traverse (move) a linked list, node by node from the first node, until the end of the list is reached. Traversing a list involves the following steps: • Assign the address of start pointer to a temp pointer. • Display the information from the data field of each node. The function traverse () is used for traversing and displaying the information stored in the list from left to right. Singly Linked List Implementation #include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next; }; struct node *head; void beginsert (); void lastinsert (); void randominsert(); void begin_delete(); void last_delete(); void random_delete(); void display(); void search(); void main () { int choice =0; while(choice != 9) { printf("nn*********Main Menu*********n"); printf("nChoose one option from the following list ...n"); printf("n===============================================n"); printf("n1.Insert in beginingn2.Insert at lastn3.Insert at any random locationn4.Delete from
  • 15. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II Beginningn 5.Delete from lastn6.Delete node after specified locationn7.Search for an elementn8.Shown9.Exitn"); printf("nEnter your choice?n"); scanf("n%d",&choice); switch(choice) { case 1: beginsert(); break; case 2: lastinsert(); break; case 3: randominsert(); break; case 4: begin_delete(); break; case 5: last_delete(); break; case 6: random_delete(); break; case 7: search(); break; case 8: display(); break; case 9: exit(0); break; default: printf("Please enter valid choice.."); } } } void beginsert() { struct node *ptr; int item; ptr = (struct node *) malloc(sizeof(struct node *)); if(ptr == NULL) { printf("nOVERFLOW");
  • 16. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II } else { printf("nEnter valuen"); scanf("%d",&item); ptr->data = item; ptr->next = head; head = ptr; printf("nNode inserted"); } } void lastinsert() { struct node *ptr,*temp; int item; ptr = (struct node*)malloc(sizeof(struct node)); if(ptr == NULL) { printf("nOVERFLOW"); } else { printf("nEnter value?n"); scanf("%d",&item); ptr->data = item; if(head == NULL) { ptr -> next = NULL; head = ptr; printf("nNode inserted"); } else { temp = head; while (temp -> next != NULL) { temp = temp -> next; } temp->next = ptr; ptr->next = NULL; printf("nNode inserted"); } } } void randominsert()
  • 17. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II { int i,loc,item; struct node *ptr, *temp; ptr = (struct node *) malloc (sizeof(struct node)); if(ptr == NULL) { printf("nOVERFLOW"); } else { printf("nEnter element value"); scanf("%d",&item); ptr->data = item; printf("nEnter the location after which you want to insert "); scanf("n%d",&loc); temp=head; for(i=0;i<loc;i++) { temp = temp->next; if(temp == NULL) { printf("ncan't insertn"); return; } } ptr ->next = temp ->next; temp ->next = ptr; printf("nNode inserted"); } } void begin_delete() { struct node *ptr; if(head == NULL) { printf("nList is emptyn"); } else { ptr = head; head = ptr->next; free(ptr); printf("nNode deleted from the begining ...n"); } } void last_delete()
  • 18. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II { struct node *ptr,*ptr1; if(head == NULL) { printf("nlist is empty"); } else if(head -> next == NULL) { head = NULL; free(head); printf("nOnly node of the list deleted ...n"); } else { ptr = head; while(ptr->next != NULL) { ptr1 = ptr; ptr = ptr ->next; } ptr1->next = NULL; free(ptr); printf("nDeleted Node from the last ...n"); } } void random_delete() { struct node *ptr,*ptr1; int loc,i; printf("n Enter the location of the node after which you want to perform deletion n"); scanf("%d",&loc); ptr=head; for(i=0;i<loc;i++) { ptr1 = ptr; ptr = ptr->next; if(ptr == NULL) { printf("nCan't delete"); return; } } ptr1 ->next = ptr ->next; free(ptr); printf("nDeleted node %d ",loc+1);
  • 19. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II } void search() { struct node *ptr; int item,i=0,flag; ptr = head; if(ptr == NULL) { printf("nEmpty Listn"); } else { printf("nEnter item which you want to search?n"); scanf("%d",&item); while (ptr!=NULL) { if(ptr->data == item) { printf("item found at location %d ",i+1); flag=0; } else { flag=1; } i++; ptr = ptr -> next; } if(flag==1) { printf("Item not foundn"); } } } void display() { struct node *ptr; ptr = head; if(ptr == NULL) { printf("Nothing to print"); } else { printf("nprinting values . . . . .n");
  • 20. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II while (ptr!=NULL) { printf("n%d",ptr->data); ptr = ptr -> next; } } } Output: *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete node after specified location 7.Search for an element 8.Show 9.Exit Enter your choice? 1 Enter value 1 Node inserted *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete node after specified location
  • 21. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II 7.Search for an element 8.Show 9.Exit Enter your choice? 2 Enter value? 2 Node inserted *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete node after specified location 7.Search for an element 8.Show 9.Exit Enter your choice? 3 Enter element value1 Enter the location after which you want to insert 1 Node inserted *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning
  • 22. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II 5.Delete from last 6.Delete node after specified location 7.Search for an element 8.Show 9.Exit Enter your choice? 8 printing values . . . . . 1 2 1 *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete node after specified location 7.Search for an element 8.Show 9.Exit Enter your choice? 2 Enter value? 123 Node inserted *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last
  • 23. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete node after specified location 7.Search for an element 8.Show 9.Exit Enter your choice? 1 Enter value 1234 Node inserted *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete node after specified location 7.Search for an element 8.Show 9.Exit Enter your choice? 4 Node deleted from the begining ... *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning
  • 24. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II 5.Delete from last 6.Delete node after specified location 7.Search for an element 8.Show 9.Exit Enter your choice? 5 Deleted Node from the last ... *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete node after specified location 7.Search for an element 8.Show 9.Exit Enter your choice? 6 Enter the location of the node after which you want to perform deletion 1 Deleted node 2 *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete node after specified location
  • 25. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II 7.Search for an element 8.Show 9.Exit Enter your choice? 8 printing values . . . . . 1 1 *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete node after specified location 7.Search for an element 8.Show 9.Exit Enter your choice? 7 Enter item which you want to search? 1 item found at location 1 item found at location 2 *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last
  • 26. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II 6.Delete node after specified location 7.Search for an element 8.Show 9.Exit Enter your choice? 9 Double Linked List: A double linked list is a two-way list in which all nodes will have two links. This helps in accessing both successor node and predecessor node from the given node position. It provides bi- directional traversing. Each node contains three fields: ● Left link. ● Data. ● Right link. The left link points to the predecessor node and the right link points to the successor node. The data field stores the required data. Many applications require searching forward and backward thru nodes of a list. For example searching for a name in a telephone directory would need forward and backward scanning thru a region of the whole list. The basic operations in a double linked list are: ● Creation. ● Insertion. ● Deletion. ● Traversing. The beginning of the double linked list is stored in a "start" pointer which points to the first node. The first node‟s left link and last node‟s right link is set to NULL. Creating a node for Double Linked List: Creating a double linked list starts with creating a node. Sufficient memory has to be allocated for creating a node. The information is stored in the memory. Double Linked List with 3 nodes:
  • 27. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II Inserting a node at the beginning: Inserting a node at the end: Inserting a node at an intermediate position: Deleting a node at the beginning:
  • 28. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II Deleting a node at the end: Deleting a node at Intermediate position: Traversal and displaying a list (Left to Right): To display the information, you have to traverse the list, node by node from the first node, until the end of the list is reached. The function traverse_left_right() is used for traversing and displaying the information stored in the list from left to right. Traversal and displaying a list (Right to Left): To display the information from right to left, you have to traverse the list, node by node from the first node, until the end of the list is reached. The function traverse_right_left() is used for traversing and displaying the information stored in the list from right to left. Menu Driven Program in C to implement all the operations of doubly linked list
  • 29. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II #include<stdio.h> #include<stdlib.h> struct node { struct node *prev; struct node *next; int data; }; struct node *head; void insertion_beginning(); void insertion_last(); void insertion_specified(); void deletion_beginning(); void deletion_last(); void deletion_specified(); void display(); void search(); void main () { int choice =0; while(choice != 9) { printf("n*********Main Menu*********n"); printf("nChoose one option from the following list ...n"); printf("n===============================================n"); printf("n1.Insert in beginingn2.Insert at lastn3.Insert at any random locationn4.Delete from Beginningn 5.Delete from lastn6.Delete the node after the given datan7.Searchn8.Shown9.Exitn"); printf("nEnter your choice?n"); scanf("n%d",&choice); switch(choice) { case 1: insertion_beginning(); break; case 2: insertion_last(); break; case 3: insertion_specified(); break; case 4: deletion_beginning(); break; case 5: deletion_last();
  • 30. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II break; case 6: deletion_specified(); break; case 7: search(); break; case 8: display(); break; case 9: exit(0); break; default: printf("Please enter valid choice.."); } } } void insertion_beginning() { struct node *ptr; int item; ptr = (struct node *)malloc(sizeof(struct node)); if(ptr == NULL) { printf("nOVERFLOW"); } else { printf("nEnter Item value"); scanf("%d",&item); if(head==NULL) { ptr->next = NULL; ptr->prev=NULL; ptr->data=item; head=ptr; } else { ptr->data=item; ptr->prev=NULL; ptr->next = head; head->prev=ptr; head=ptr; }
  • 31. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II printf("nNode insertedn"); } } void insertion_last() { struct node *ptr,*temp; int item; ptr = (struct node *) malloc(sizeof(struct node)); if(ptr == NULL) { printf("nOVERFLOW"); } else { printf("nEnter value"); scanf("%d",&item); ptr->data=item; if(head == NULL) { ptr->next = NULL; ptr->prev = NULL; head = ptr; } else { temp = head; while(temp->next!=NULL) { temp = temp->next; } temp->next = ptr; ptr ->prev=temp; ptr->next = NULL; } } printf("nnode insertedn"); } void insertion_specified() { struct node *ptr,*temp; int item,loc,i; ptr = (struct node *)malloc(sizeof(struct node)); if(ptr == NULL) { printf("n OVERFLOW");
  • 32. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II } else { temp=head; printf("Enter the location"); scanf("%d",&loc); for(i=0;i<loc;i++) { temp = temp->next; if(temp == NULL) { printf("n There are less than %d elements", loc); return; } } printf("Enter value"); scanf("%d",&item); ptr->data = item; ptr->next = temp->next; ptr -> prev = temp; temp->next = ptr; temp->next->prev=ptr; printf("nnode insertedn"); } } void deletion_beginning() { struct node *ptr; if(head == NULL) { printf("n UNDERFLOW"); } else if(head->next == NULL) { head = NULL; free(head); printf("nnode deletedn"); } else { ptr = head; head = head -> next; head -> prev = NULL; free(ptr); printf("nnode deletedn"); }
  • 33. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II } void deletion_last() { struct node *ptr; if(head == NULL) { printf("n UNDERFLOW"); } else if(head->next == NULL) { head = NULL; free(head); printf("nnode deletedn"); } else { ptr = head; if(ptr->next != NULL) { ptr = ptr -> next; } ptr -> prev -> next = NULL; free(ptr); printf("nnode deletedn"); } } void deletion_specified() { struct node *ptr, *temp; int val; printf("n Enter the data after which the node is to be deleted : "); scanf("%d", &val); ptr = head; while(ptr -> data != val) ptr = ptr -> next; if(ptr -> next == NULL) { printf("nCan't deleten"); } else if(ptr -> next -> next == NULL) { ptr ->next = NULL; } else { temp = ptr -> next; ptr -> next = temp -> next;
  • 34. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II temp -> next -> prev = ptr; free(temp); printf("nnode deletedn"); } } void display() { struct node *ptr; printf("n printing values...n"); ptr = head; while(ptr != NULL) { printf("%dn",ptr->data); ptr=ptr->next; } } void search() { struct node *ptr; int item,i=0,flag; ptr = head; if(ptr == NULL) { printf("nEmpty Listn"); } else { printf("nEnter item which you want to search?n"); scanf("%d",&item); while (ptr!=NULL) { if(ptr->data == item) { printf("nitem found at location %d ",i+1); flag=0; break; } else { flag=1; } i++; ptr = ptr -> next; } if(flag==1) { printf("nItem not foundn");
  • 35. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II } } } Output *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete the node after the given data 7.Search 8.Show 9.Exit Enter your choice? 8 printing values... *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete the node after the given data 7.Search 8.Show 9.Exit Enter your choice? 1 Enter Item value12
  • 36. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II Node inserted *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete the node after the given data 7.Search 8.Show 9.Exit Enter your choice? 1 Enter Item value123 Node inserted *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete the node after the given data 7.Search 8.Show 9.Exit Enter your choice? 1 Enter Item value1234
  • 37. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II Node inserted *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete the node after the given data 7.Search 8.Show 9.Exit Enter your choice? 8 printing values... 1234 123 12 *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete the node after the given data 7.Search 8.Show 9.Exit Enter your choice? 2 Enter value89
  • 38. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II node inserted *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete the node after the given data 7.Search 8.Show 9.Exit Enter your choice? 3 Enter the location1 Enter value12345 node inserted *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete the node after the given data 7.Search 8.Show 9.Exit Enter your choice? 8 printing values... 1234 123
  • 39. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II 12345 12 89 *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete the node after the given data 7.Search 8.Show 9.Exit Enter your choice? 4 node deleted *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete the node after the given data 7.Search 8.Show 9.Exit Enter your choice? 5 node deleted *********Main Menu*********
  • 40. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete the node after the given data 7.Search 8.Show 9.Exit Enter your choice? 8 printing values... 123 12345 *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete the node after the given data 7.Search 8.Show 9.Exit Enter your choice? 6 Enter the data after which the node is to be deleted : 123 *********Main Menu********* Choose one option from the following list ...
  • 41. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete the node after the given data 7.Search 8.Show 9.Exit Enter your choice? 8 printing values... 123 *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete the node after the given data 7.Search 8.Show 9.Exit Enter your choice? 7 Enter item which you want to search? 123 item found at location 1 *********Main Menu********* Choose one option from the following list ... ===============================================
  • 42. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete the node after the given data 7.Search 8.Show 9.Exit Enter your choice? 6 Enter the data after which the node is to be deleted : 123 Can't delete *********Main Menu********* Choose one option from the following list ... =============================================== 1.Insert in begining 2.Insert at last 3.Insert at any random location 4.Delete from Beginning 5.Delete from last 6.Delete the node after the given data 7.Search 8.Show 9.Exit Enter your choice? 9 Exited.. Circular Single Linked List: It is just a single linked list in which the link field of the last node points back to the address of the first node. A circular linked list has no beginning and no end. It is necessary to establish a special pointer called start pointer always pointing to the first node of the list. Circular linked lists are frequently used instead of ordinary linked list because many operations are much easier to implement. In circular linked list no null pointers are used, hence all pointers contain valid address.
  • 43. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II Creating a circular single Linked List with „n‟ number of nodes: The basic operations in a circular single linked list are: • Creation. • Insertion. • Deletion. • Traversing. Inserting a node at the beginning: Inserting a node at the end: Deleting a node at the beginning:
  • 44. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II Deleting a node at the end: Menu-driven program in C implementing all operations on circular singly linked list #include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next; }; struct node *head; void beginsert (); void lastinsert (); void randominsert(); void begin_delete(); void last_delete(); void random_delete(); void display(); void search(); void main () { int choice =0; while(choice != 7) { printf("n*********Main Menu*********n"); printf("nChoose one option from the following list ...n"); printf("n===============================================n");
  • 45. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II printf("n1.Insert in beginingn2.Insert at lastn3.Delete from Beginningn4.Delete from lastn5.Search for an elementn6.Shown7.Exitn"); printf("nEnter your choice?n"); scanf("n%d",&choice); switch(choice) { case 1: beginsert(); break; case 2: lastinsert(); break; case 3: begin_delete(); break; case 4: last_delete(); break; case 5: search(); break; case 6: display(); break; case 7: exit(0); break; default: printf("Please enter valid choice.."); } } } void beginsert() { struct node *ptr,*temp; int item; ptr = (struct node *)malloc(sizeof(struct node)); if(ptr == NULL) { printf("nOVERFLOW"); } else { printf("nEnter the node data?"); scanf("%d",&item); ptr -> data = item; if(head == NULL)
  • 46. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II { head = ptr; ptr -> next = head; } else { temp = head; while(temp->next != head) temp = temp->next; ptr->next = head; temp -> next = ptr; head = ptr; } printf("nnode insertedn"); } } void lastinsert() { struct node *ptr,*temp; int item; ptr = (struct node *)malloc(sizeof(struct node)); if(ptr == NULL) { printf("nOVERFLOWn"); } else { printf("nEnter Data?"); scanf("%d",&item); ptr->data = item; if(head == NULL) { head = ptr; ptr -> next = head; } else { temp = head; while(temp -> next != head) { temp = temp -> next; } temp -> next = ptr; ptr -> next = head; }
  • 47. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II printf("nnode insertedn"); } } void begin_delete() { struct node *ptr; if(head == NULL) { printf("nUNDERFLOW"); } else if(head->next == head) { head = NULL; free(head); printf("nnode deletedn"); } else { ptr = head; while(ptr -> next != head) ptr = ptr -> next; ptr->next = head->next; free(head); head = ptr->next; printf("nnode deletedn"); } } void last_delete() { struct node *ptr, *preptr; if(head==NULL) { printf("nUNDERFLOW"); } else if (head ->next == head) { head = NULL; free(head); printf("nnode deletedn"); } else { ptr = head;
  • 48. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II while(ptr ->next != head) { preptr=ptr; ptr = ptr->next; } preptr->next = ptr -> next; free(ptr); printf("nnode deletedn"); } } void search() { struct node *ptr; int item,i=0,flag=1; ptr = head; if(ptr == NULL) { printf("nEmpty Listn"); } else { printf("nEnter item which you want to search?n"); scanf("%d",&item); if(head ->data == item) { printf("item found at location %d",i+1); flag=0; } else { while (ptr->next != head) { if(ptr->data == item) { printf("item found at location %d ",i+1); flag=0; break; } else { flag=1; } i++; ptr = ptr -> next; }
  • 49. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II } if(flag != 0) { printf("Item not foundn"); } } } void display() { struct node *ptr; ptr=head; if(head == NULL) { printf("nnothing to print"); } else { printf("n printing values ... n"); while(ptr -> next != head) { printf("%dn", ptr -> data); ptr = ptr -> next; } printf("%dn", ptr -> data); } } Circular Double Linked List: A circular double linked list has both successor pointer and predecessor pointer in circular manner. The objective behind considering circular double linked list is to simplify the insertion and deletion operations performed on double linked list. In circular double linked list the right link of the right most node points back to the start node and left link of the first node points to the last node. A circular double linked list is shown in figure
  • 50. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II Creating a Circular Double Linked List with „n‟ number of nodes The basic operations in a circular double linked list are: • Creation. • Insertion. • Deletion. • Traversing. Inserting a node at the beginning: Inserting a node at the end:
  • 51. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II Inserting a node at an intermediate position: Deleting a node at the beginning: Deleting a node at the end:
  • 52. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II Deleting a node at Intermediate position: C program to implement all the operations on circular doubly linked list #include<stdio.h> #include<stdlib.h> struct node { struct node *prev; struct node *next; int data; }; struct node *head; void insertion_beginning(); void insertion_last(); void deletion_beginning(); void deletion_last(); void display(); void search(); void main () { int choice =0; while(choice != 9) { printf("n*********Main Menu*********n"); printf("nChoose one option from the following list ...n"); printf("n===============================================n"); printf("n1.Insert in Beginningn2.Insert at lastn3.Delete from Beginningn4.Delete from
  • 53. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II lastn5.Searchn6.Shown7.Exitn"); printf("nEnter your choice?n"); scanf("n%d",&choice); switch(choice) { case 1: insertion_beginning(); break; case 2: insertion_last(); break; case 3: deletion_beginning(); break; case 4: deletion_last(); break; case 5: search(); break; case 6: display(); break; case 7: exit(0); break; default: printf("Please enter valid choice.."); } } } void insertion_beginning() { struct node *ptr,*temp; int item; ptr = (struct node *)malloc(sizeof(struct node)); if(ptr == NULL) { printf("nOVERFLOW"); } else { printf("nEnter Item value"); scanf("%d",&item); ptr->data=item; if(head==NULL) { head = ptr;
  • 54. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II ptr -> next = head; ptr -> prev = head; } else { temp = head; while(temp -> next != head) { temp = temp -> next; } temp -> next = ptr; ptr -> prev = temp; head -> prev = ptr; ptr -> next = head; head = ptr; } printf("nNode insertedn"); } } void insertion_last() { struct node *ptr,*temp; int item; ptr = (struct node *) malloc(sizeof(struct node)); if(ptr == NULL) { printf("nOVERFLOW"); } else { printf("nEnter value"); scanf("%d",&item); ptr->data=item; if(head == NULL) { head = ptr; ptr -> next = head; ptr -> prev = head; } else { temp = head; while(temp->next !=head) { temp = temp->next; } temp->next = ptr;
  • 55. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II ptr ->prev=temp; head -> prev = ptr; ptr -> next = head; } } printf("nnode insertedn"); } void deletion_beginning() { struct node *temp; if(head == NULL) { printf("n UNDERFLOW"); } else if(head->next == head) { head = NULL; free(head); printf("nnode deletedn"); } else { temp = head; while(temp -> next != head) { temp = temp -> next; } temp -> next = head -> next; head -> next -> prev = temp; free(head); head = temp -> next; } } void deletion_last() { struct node *ptr; if(head == NULL) { printf("n UNDERFLOW"); } else if(head->next == head) { head = NULL; free(head); printf("nnode deletedn"); }
  • 56. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II else { ptr = head; if(ptr->next != head) { ptr = ptr -> next; } ptr -> prev -> next = head; head -> prev = ptr -> prev; free(ptr); printf("nnode deletedn"); } } void display() { struct node *ptr; ptr=head; if(head == NULL) { printf("nnothing to print"); } else { printf("n printing values ... n"); while(ptr -> next != head) { printf("%dn", ptr -> data); ptr = ptr -> next; } printf("%dn", ptr -> data); } } void search() { struct node *ptr; int item,i=0,flag=1; ptr = head; if(ptr == NULL) { printf("nEmpty Listn"); } else {
  • 57. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II printf("nEnter item which you want to search?n"); scanf("%d",&item); if(head ->data == item) { printf("item found at location %d",i+1); flag=0; } else { while (ptr->next != head) { if(ptr->data == item) { printf("item found at location %d ",i+1); flag=0; break; } else { flag=1; } i++; ptr = ptr -> next; } } if(flag != 0) { printf("Item not foundn"); } } } Stacks Primitive Operations: A stack is a container of objects that are inserted and removed according to the last-in first-out (LIFO) principle. In the pushdown stacks only two operations are allowed: push the item into the stack, and pop the item out of the stack. A stack is a limited access data structure - elements can be added and removed from the stack only at the top. Push adds an item to the top of the stack, pop removes the item from the top. A helpful analogy is to think of a stack of books; you can remove only the top book, also you can add a new book on the top. A stack may be implemented to have a bounded capacity. If the stack is full and does not contain enough space to accept an entity to be pushed, the stack is then considered to be in an overflow state. The pop operation removes an item from the top of the stack. A pop either reveals previously concealed items or results in an empty stack, but, if the stack is empty, it goes into underflow state, which means no items are present in stack to be removed.
  • 58. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II Stack (ADT) Data Structure: Stack is an Abstract data structure (ADT) works on the principle Last In First Out (LIFO). The last element add to the stack is the first element to be delete. Insertion and deletion can be takes place at one end called TOP. It looks like one side closed tube. ● The add operation of the stack is called push operation ● The delete operation is called as pop operation. ● Push operation on a full stack causes stack overflow. ● Pop operation on an empty stack causes stack underflow. ● SP is a pointer, which is used to access the top element of the stack. ● If you push elements that are added at the top of the stack; ● In the same way when we pop the elements, the element at the top of the stack is deleted. Operations of stack: There are two operations applied on stack they are 1. push 2. pop. While performing push & pop operations the following test must be conducted on the stack. 1) Stack is empty or not 2) Stack is full or not Push: Push operation is used to add new elements in to the stack. At the time of addition first check the stack
  • 59. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II is full or not. If the stack is full it generates an error message "stack overflow". Pop: Pop operation is used to delete elements from the stack. At the time of deletion first check the stack is empty or not. If the stack is empty it generates an error message "stack underflow". Representation of a Stack using Arrays: Let us consider a stack with 6 elements capacity. This is called as the size of the stack. The number of elements to be added should not exceed the maximum size of the stack. If we attempt to add new element beyond the maximum size, we will encounter a stack overflow condition. Similarly, you cannot remove elements beyond the base of the stack. If such is the case, we will reach a stack underflow condition. When a element is added to a stack, the operation is performed by push(). When an element is taken off from the stack, the operation is performed by pop(). Source code for stack operations, using array: STACK: Stack is a linear data structure which works under the principle of last in first out. Basic operations: push, pop, display. 1. PUSH: if (top==MAX), display Stack overflow else reading the data and making stack [top] =data and incrementing the top value by doing top++. 2. POP: if (top==0), display Stack underflow else printing the element at the top of the stack and decrementing the top value by doing the top. 3. DISPLAY: IF (TOP==0), display Stack is empty else printing the elements in the stack from stack [0] to stack [top]. Example: #include <stdio.h>
  • 60. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II int stack[100],i,j,choice=0,n,top=-1; void push(); void pop(); void show(); void main () { printf("Enter the number of elements in the stack "); scanf("%d",&n); printf("*********Stack operations using array*********"); printf("n----------------------------------------------n"); while(choice != 4) { printf("Chose one from the below options...n"); printf("n1.Pushn2.Popn3.Shown4.Exit"); printf("n Enter your choice n"); scanf("%d",&choice); switch(choice) { case 1: { push(); break; } case 2: { pop(); break; } case 3: { show(); break; } case 4: { printf("Exiting...."); break; } default: { printf("Please Enter valid choice "); } }; } }
  • 61. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II void push () { int val; if (top == n ) printf("n Overflow"); else { printf("Enter the value?"); scanf("%d",&val); top = top +1; stack[top] = val; } } void pop () { if(top == -1) printf("Underflow"); else top = top -1; } void show() { for (i=top;i>=0;i--) { printf("%dn",stack[i]); } if(top == -1) { printf("Stack is empty"); } } Linked List Implementation of Stacks The first implementation of a stack uses a singly linked list. We perform a push by inserting at the front of the list. We perform a pop by deleting the element at the front of the list. A top operation merely examines the element at the front of the list, returning its value. Sometimes the pop and top operations are combined into one. Creating an empty stack is also simple. We merely create a header node; make_null sets the next pointer to NULL. The push is implemented as an insertion into the front of a linked list, where the front of the
  • 62. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II list serves as the top of the stack. The top is performed by examining the element in the first position of the list. The pop will delete from the front of the list. It should be clear that all the operations take constant time, because less a loop that depends on this size. Drawbacks and solution These implementations uses the calls to malloc and free are expensive, especially in comparison to the pointer manipulation routines. Some of this can be avoided by using a second stack, which is initially empty. When a cell is to be disposed from the first stack, it is merely placed on the second stack. Then, when new cells are needed for the first stack, the second stack is checked first. Type declaration for linked list implementation of the stack ADT struct Node; typedef struct node *ptrToNode; typedef ptrToNode Stack; int IsEmpty(Stack S); Stack CreateSatck(void); void DisposeStack(Stack S); void MakeEmpty(Stack S); void Push(ElementType X, Stack S); ElementType Top (Stack S); Void Pop(Stack S);
  • 63. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II struct node { Element_type element; PtrToNode next; }; Routine to test whether a stack is empty-linked list implementation This routine checks whether Stack is empty or not. If it is not empty it will return a pointer to the stack. Otherwise return NULL int is_empty( STACK S ) { return( S->next == NULL ); } Routine to create an empty stack-linked list implementation This routine creates a Stack and return a pointer of the stack. Otherwise return a warning to say Stack is not created. STACK create_stack( void ) { STACK S; S = malloc( sizeof( struct node ) ); if( S == NULL ) fatal_error("Out of space!!!"); return S; }
  • 64. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II Routine to make the stack as empty-linked list implementation This routine makes Stack as empty and return NULL pointer. Void makeEmpty( STACK S ) { if( S == NULL ) error ("Must use create_stack first"); else while (!IsEmpty(S)) pop(S); } Routine to push onto a stack-linked list implementation This routine is to insert the new element onto the top of the stack. Void push( element_type x, STACK S ) { node_ptr tmp_cell; tmp_cell = (node_ptr) malloc( sizeof ( struct node ) ); if( tmp_cell == NULL ) fatal_error("Out of space!!!"); else { tmp_cell->element = x; tmp_cell->next = S->next; S->next = tmp_cell; } }
  • 65. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II Routine to return top element in a stack--linked list implementation This routine is to return the topmost element from the stack. element_type top( STACK S ) { if( is_empty( S ) ) error("Empty stack"); else return S->next->element; } Routine to pop from a stack--linked list implementation This routine is to delete the topmost element from the stack. Void pop( STACK S ) { PtrToNode first_cell; if( is_empty( S ) ) error("Empty stack"); else { first_cell = S->next; S->next = S->next->next;
  • 66. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II free( first_cell ); } } Stack Applications Stack is used for the following applications. 1. Reversing of the string 2. Tower’s of Hanoi’s problem 3. Balancing Symbols 4. Conversion of Infix to postfix expression 5. Conversion of Infix to prefix expression 6. Evaluation of Postfix expression 7. Used in Function calls Balancing Symbols Compilers check your programs for syntax errors, but frequently a lack of one symbol (such as a missing brace or comment starter) will cause the compiler to spill out a hundred lines of diagnostics without identifying the real error. A useful tool in this situation is a program that checks whether everything is balanced. Thus, every right brace, bracket, and parenthesis must correspond to their left counterparts. The sequence [()] is legal, but [(]) is wrong. That it is easy to check these things. For simplicity, we will just check for balancing of parentheses, brackets, and braces and ignore any other character that appears.
  • 67. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II The simple algorithm uses a stack and is as follows: ● Make an empty stack. ● Read characters until end of file. ● If the character is an open anything, push it onto the stack. ● If it is a close anything, then ✔ If the stack is empty report an error. ✔ Otherwise, pop the stack. ✔ If the symbol popped is not the corresponding opening symbol, then report an error. ● At end of file, if the stack is not empty report an error. Expression: Expression is defined as a collection of operands and operators. The operators can be arithmetic, logical or Boolean operators. Rules for expression ✔ No two operand should be continuous ✔ No two operator should be continuous Types of expression: Based on the position of the operator, it is classified into three. 1. Infix Expression / Standard notation 2. Prefix Expression/ Polished notation 3. Postfix Expression / Reversed Polished notation Infix Expression: In an expression if the operator is placed in between the operands, then it is called as Infix Expression. Eg : A+B
  • 68. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II Prefix Expression: In an expression if the operator is placed before the operands, then it is called as Prefix Expression. Eg : +AB Postfix Expression: In an expression if the operator is placed after the operands, then it is called as Postfix Expression. Eg : AB+ Conversion of infix to Postfix Expressions Stack is used to convert an expression in standard form (otherwise known as infix) into postfix. We will concentrate on a small version of the general problem by allowing only the operators +, *, and (, ), and insisting on the usual precedence rules. Suppose we want to convert the infix expression a + b * c + ( d * e + f ) * g . A correct answer is a b c * + d e * f + g * +. Algorithm: 1. We start with an initially empty stack 2. When an operand is read, it is immediately placed onto the output. 3. Operators are not immediately placed onto the output, so they must be saved somewhere. The correct thing to do is to place operators that have been seen, but not placed on the output, onto the stack. We will also stack left parentheses when they are encountered. 4. If we see a right parenthesis, then we pop the stack, writing symbols until we encounter a (corresponding) left parenthesis, which is popped but not output.
  • 69. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II 5. If we see any other symbol ('+','*', '(' ), then we pop entries from the stack until we find an entry of lower priority. One exception is that we never remove a '(' from the stack except when processing a ')'. For the purposes of this operation, '+' has lowest priority and '(' highest. When the popping is done, we push the operand onto the stack. 6. Finally, if we read the end of input, we pop the stack until it is empty, writing symbols onto the output. To see how this algorithm performs, we will convert the infix expression into its postfix form. a + b * c + (d * e + f) * g First, the symbol a is read, so it is passed through to the output. Then '+' is read and pushed onto the stack. Next b is read and passed through to the output. Then the stack will be as follows. Next a '*' is read. The top entry on the operator stack has lower precedence than '*', so nothing is output and '*' is put on the stack. Next, c is read and output. The next symbol is a '+'. Checking the stack, we find that we will pop a '*' and place it on the output, pop the other '+', which is not of lower but equal priority, on the stack, and then push the '+'. The next symbol read is an '(', which, being of highest precedence, is placed on the stack. Then d is read and output.
  • 70. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II We continue by reading a '*'. Since open parentheses do not get removed except when a closed parenthesis is being processed, there is no output. Next, e is read and output. The next symbol read is a '+'. We pop and output '*' and then push '+'. Then we read and output f. . Now we read a ')', so the stack is emptied back to the '('. We output a '+' 0nto the stack. We read a '*' next; it is pushed onto the stack. Then g is read and output. The input is now empty, so we pop and output symbols from the stack until it is empty. As before, this conversion requires only O(n) time and works in one pass through the input.
  • 71. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II We can add subtraction and division to this repertoire by assigning subtraction and addition equal priority and multiplication and division equal priority. A subtle point is that the expression a - b - c will be converted to ab - c- and not abc - -. Our algorithm does the right thing, because these operators associate from left to right. This is not necessarily the case in general, since exponentiation associates right to left: 223 = 28 = 256 not 43 = 64. Evaluation of a Postfix Expression Algorithm: When a number is seen, it is pushed onto the stack; When an operator is seen, the operator is applied to the two numbers (symbols) that are popped from the stackand the result is pushed onto the stack. For example, the postfix expression 6 5 2 3 + 8 * + 3 + * is evaluated as follows: The first four symbols are placed on the stack. The resulting stack is TopofStack 3 2 5 6 Next a '+' is read, so 3 and 2 are popped from the stack and their sum, 5, is pushed. TopofStack 5 5 6
  • 72. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II Next 8 is pushed. TopofStack 8 5 5 6 Now a '*' is seen, so 8 and 5 are popped as 8 * 5 = 40 is pushed. TopofStack 40 5 6 Next a '+' is seen, so 40 and 5 are popped and 40 + 5 = 45 is pushed. TopofStack 45 6 Now, 3 is pushed. TopofStack 3 45 6 Next '+' pops 3 and 45 and pushes 45 + 3 = 48. TopofStack 48 6 Finally, a '*' is seen and 48 and 6 are popped, the result 6 * 48 = 288 is pushed.
  • 73. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II TopofStack 288 The time to evaluate a postfix expression is O(n), because processing each element in the input consists of stack operations and thus takes constant time. The algorithm to do so is very simple. Advantage of postfix expression: When an expression is given in postfix notation, there is no need to know any precedence rules; Menu Driven program in C implementing all the stack operations using linked list : #include <stdio.h> #include <stdlib.h> void push(); void pop(); void display(); struct node { int val; struct node *next; }; struct node *head; void main () { int choice=0; printf("n*********Stack operations using linked list*********n"); printf("n----------------------------------------------n"); while(choice != 4) { printf("nnChose one from the below options...n"); printf("n1.Pushn2.Popn3.Shown4.Exit"); printf("n Enter your choice n"); scanf("%d",&choice); switch(choice) { case 1: { push(); break; } case 2: { pop();
  • 74. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II break; } case 3: { display(); break; } case 4: { printf("Exiting...."); break; } default: { printf("Please Enter valid choice "); } }; } } void push () { int val; struct node *ptr = (struct node*)malloc(sizeof(struct node)); if(ptr == NULL) { printf("not able to push the element"); } else { printf("Enter the value"); scanf("%d",&val); if(head==NULL) { ptr->val = val; ptr -> next = NULL; head=ptr; } else { ptr->val = val; ptr->next = head; head=ptr; } printf("Item pushed"); } }
  • 75. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II void pop() { int item; struct node *ptr; if (head == NULL) { printf("Underflow"); } else { item = head->val; ptr = head; head = head->next; free(ptr); printf("Item popped"); } } void display() { int i; struct node *ptr; ptr=head; if(ptr == NULL) { printf("Stack is emptyn"); } else { printf("Printing Stack elements n"); while(ptr!=NULL) { printf("%dn",ptr->val); ptr = ptr->next; } } } The Queue ADT Queue is also a list in which insertion is done at one end, whereas deletion is performed at the other end. Insertion will be at rear end of the queue and deletion will be at front of the queue. It is also called as FIFO (First In First Out) which means the element which inserted first will be removed first from the queue.
  • 76. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II Queue Model The basic operations on a queue are 1. enqueue, which inserts an element at the end of the list (called the rear) 2. dequeue, which deletes (and returns) the element at the start of the list (known as the front). Abstract model of a queue Array Implementation of Queues ● Like stacks, both the linked list and array implementations give fast O(1) running times for every operation. The linked list implementation is straightforward and left as an exercise. We will now discuss an array implementation of queues. ● For each queue data structure, we keep an array, QUEUE[], and the positions q_front and q_rear, which represent the ends of the queue. We also keep track of the number of elements that are actually in the queue, q_size. The following figure shows a queue in some intermediate state. ● By the way, the cells that are blanks have undefined values in them. In particular, the first two cells have elements that used to be in the queue. ● To enqueue an element x, we increment q_size and q_rear, then set QUEUE[q_rear] = x.
  • 77. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II ● To dequeue an element, we set the return value to QUEUE[q_front], decrement q_size, and then increment q_front.. After 10 enqueues, the queue appears to be full, since q_front is now 10, and the next enqueue would be in a nonexistent position. ● However, there might only be a few elements in the queue, because several elements may have already been dequeued. ● The simple solution is that whenever q_front or q_rear gets to the end of the array, it is wrapped around to the beginning. This is known as a circular array implementation. If incrementing either q_rear or q_front causes it to go past the array, the value is reset to the first position in the array. There are two warnings about the circular array implementation of queues. ● First, it is important to check the queue for emptiness, because a dequeue when the queue is empty will return an undefined value. ● Secondly, some programmers use different ways of representing the front and rear of a queue. For instance, some do not use an entry to keep track of the size, because they rely on the base case that when the queue is empty, q_rear = q_front - 1. If the size is not part of the structure, then if the array size is A_SIZE, the queue is full when there are A_SIZE -1 elements. In applications where you are sure that the number of enqueues is not larger than the size of the queue, the wraparound is not necessary. The routine queue_create and queue_dispose routines also need to be provided. We also provide routines to test whether a queue is empty and to make an empty queue. Notice that q_rear is preinitialized to 1 before q_front. The final operation we will write is the enqueue routine. Type declarations for queue--array implementation struct QueueRecord { int Capacity;
  • 78. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II int Front; int Rear; int Size; /* Current # of elements in Q */ ElementType *Array; }; typedef struct QueueRecord * Queue; Routine to test whether a queue is empty-array implementation int isempty( Queue Q ) { return( Q->q_size == 0 ); } Routine to make an empty queue-array implementation Void makeempty ( Queue Q ) { Q->size = 0; Q->Front = -1; Q->Rear = -1; }
  • 79. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II Routines to enqueue-array implementation static int succ(int value, Queue Q ) { if( ++value = = Q->Capacity )
  • 80. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II value = 0; return value; } Void enqueue( Elementtype x, Queue Q ) { if( isfull( Q ) ) error("Full queue"); else { Q->Size++; Q->Rear = succ( Q->Rear, Q ); Q- >Array[ Q->Rear ] = x; } } Applications of Queues The applications are, 1. When jobs are submitted to a printer, they are arranged in order of arrival. Then jobs sent to a line printer are placed on a queue. 2. Lines at ticket counters are queues, because service is first-come first-served. 3. Another example concerns computer networks. There are many network setups of personal computers in which the disk is attached to one machine, known as the file server. 4. Users on other machines are given access to files on a first-come first-served basis, so the data structure is a queue.
  • 81. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II Circular Queue:
  • 82. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II NOTES 82 In Circular Queue, the insertion of a new element is performed at the very first locations of the queue if the last location of the queue is full, in which the first element comes after the last element. Advantages: It overcomes the problem of unutilized space in linear queue, when it is implemented as arrays. To perform the insertion of the element to the queue, the position of the element is calculated as rear= (rear+1) % queue_size and set Q[rear]=value. Similarly the element deleted from the queue using front = (front + 1) % queue_size. Enqueue: This routine insert the new element at rear position of the circular queue.
  • 83. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II NOTES 83 Dequeue: This routine deletes the element from the front of the circular queue. void CQ_dequeue( ) { If(front==-1 && rear==-1) Print(“Queue is empty”); Else { Temp=CQueue[front]; If(front==rear) Front=rear=- 1; Else Front=(front+1)% maxsize; } }
  • 84. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II NOTES 84 Priority queue A priority queue is an abstract data type that behaves similarly to the normal queue except that each element has some priority, i.e., the element with the highest priority would come first in a priority queue. The priority of the elements in a priority queue will determine the order in which elements are removed from the priority queue. The priority queue supports only comparable elements, which means that the elements are either arranged in an ascending or descending order. For example, suppose we have some values like 1, 3, 4, 8, 14, 22 inserted in a priority queue with an ordering imposed on the values is from least to the greatest. Therefore, the 1 number would be having the highest priority while 22 will be having the lowest priority. Characteristics of a Priority queue A priority queue is an extension of a queue that contains the following characteristics: o Every element in a priority queue has some priority associated with it. o An element with the higher priority will be deleted before the deletion of the lesser priority. o If two elements in a priority queue have the same priority, they will be arranged using the FIFO principle. Types of Priority Queue There are two types of priority queue: o Ascending order priority queue: In ascending order priority queue, a lower priority number is given as a higher priority in a priority. For example, we take the numbers from 1 to 5 arranged in an ascending order like 1,2,3,4,5; therefore, the smallest number, i.e., 1 is given as the highest priority in a priority queue. o Descending order priority queue: In descending order priority queue, a higher priority number is given as a higher priority in a priority. For example, we take the numbers from 1 to 5 arranged in descending order like 5, 4, 3, 2, 1; therefore, the largest number, i.e., 5 is given as the highest priority in a priority
  • 85. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II NOTES 85 queue. Representation of priority queue Now, we will see how to represent the priority queue through a one-way list. We will create the priority queue by using the list given below in which INFO list contains the data elements, PRN list contains the priority numbers of each data element available in the INFO list, and LINK basically contains the address of the next node. Priority Queue Operations The common operations that we can perform on a priority queue are insertion, deletion and peek. Let's see how we can maintain the heap data structure. o Inserting the element in a priority queue (max heap) If we insert an element in a priority queue, it will move to the empty slot by looking from top to bottom and left to right. If the element is not in a correct place then it is compared with the parent node; if it is found out of order, elements are swapped. This process continues until the element is placed in a correct position.
  • 86. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II NOTES 86 o Removing the minimum element from the priority queue As we know that in a max heap, the maximum element is the root node. When we remove the root node, it creates an empty slot. The last inserted element will be added in this empty slot. Then, this element is compared with the child nodes, i.e., left-child and right child, and swap with the smaller of the two. It keeps moving down the tree until the heap property is restored. Applications of Priority queue The following are the applications of the priority queue: o It is used in the Dijkstra's shortest path algorithm. o It is used in prim's algorithm o It is used in data compression techniques like Huffman code. o It is used in heap sort. o It is also used in operating system like priority scheduling, load balancing and interrupt handling. Program to create the priority queue using the binary max heap. #include <stdio.h> #include <stdio.h> int heap[40]; int size=-1; // retrieving the parent node of the child node int parent(int i) { return (i - 1) / 2; } // retrieving the left child of the parent node. int left_child(int i) { return i+1; } // retrieving the right child of the parent
  • 87. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II NOTES 87 int right_child(int i) { return i+2; } // Returning the element having the highest priority int get_Max() { return heap[0]; } //Returning the element having the minimum priority int get_Min() { return heap[size]; } // function to move the node up the tree in order to restore the heap property. void moveUp(int i) { while (i > 0) { // swapping parent node with a child node if(heap[parent(i)] < heap[i]) { int temp; temp=heap[parent(i)]; heap[parent(i)]=heap[i]; heap[i]=temp; } // updating the value of i to i/2 i=i/2; } } //function to move the node down the tree in order to restore the heap property. void moveDown(int k) { int index = k; // getting the location of the Left Child int left = left_child(k); if (left <= size && heap[left] > heap[index]) { index = left; }
  • 88. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II NOTES 88 // getting the location of the Right Child int right = right_child(k); if (right <= size && heap[right] > heap[index]) { index = right; } // If k is not equal to index if (k != index) { int temp; temp=heap[index]; heap[index]=heap[k]; heap[k]=temp; moveDown(index); } } // Removing the element of maximum priority void removeMax() { int r= heap[0]; heap[0]=heap[size]; size=size-1; moveDown(0); } //inserting the element in a priority queue void insert(int p) { size = size + 1; heap[size] = p; // move Up to maintain heap property moveUp(size); } //Removing the element from the priority queue at a given index i. void delete(int i) { heap[i] = heap[0] + 1; // move the node stored at ith location is shifted to the root node moveUp(i); // Removing the node having maximum priority removeMax(); }
  • 89. 191GES205T PROGRAMMING AND DATA STRUCTURES USING C UNIT-II NOTES 89 int main() { // Inserting the elements in a priority queue insert(20); insert(19); insert(21); insert(18); insert(12); insert(17); insert(15); insert(16); insert(14); int i=0; printf("Elements in a priority queue are : "); for(int i=0;i<=size;i++) { printf("%d ",heap[i]); } delete(2); // deleting the element whose index is 2. printf("nElements in a priority queue after deleting the element are : "); for(int i=0;i<=size;i++) { printf("%d ",heap[i]); } int max=get_Max(); printf("nThe element which is having the highest priority is %d: ",max); int min=get_Min(); printf("nThe element which is having the minimum priority is : %d",min); return 0; }