Vous êtes sur la page 1sur 41

DATA STRUCTURES

UNIT-I

Basics Regarding Algorithm:


Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a certain order
to get the desired output.
Algorithms are generally created independent of underlying languages, i.e. an algorithm can be
implemented in more than one programming language.
Characteristics Of Algorithm:
There is no all procedures can be called an algorithm. An algorithm should have the following characteristics
Unambiguous Algorithm should be clear and unambiguous. Each of its steps (or phases), and their
inputs/outputs should be clear and must lead to only one meaning.
Input An algorithm should have 0 or more well-defined inputs.
Output An algorithm should have 1 or more well-defined outputs, and should match the desired output.
Finiteness Algorithms must terminate after a finite number of steps.
Feasibility should be feasible with the available resources.
Independent an algorithm should have step-by-step directions, which should be independent of any
programming code.

Efficiency of an algorithm can be analyzed at two different stages, before implementation and after
implementation. They are the following
A Priori Analysis this is a theoretical analysis of an algorithm. Efficiency of an algorithm is measured
by assuming that all other factors, for example, processor speed, are constant and have no effect on the
implementation.
A Posterior Analysis this is an empirical analysis of an algorithm. The selected algorithm is
implemented using programming language. This is then executed on target computer machine. In this
analysis, actual statistics like running time and space required are collected.
Algorithm analysis deals with the execution or running time of various operations involved. The running time of an
operation can be defined as the number of computer instructions executed per operation.

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

1. Time Complexity

2. Space Complexity

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

An algorithm generally requires space for following components:

Bit Institute Of Technology, Hindupur. Page 1


DATA STRUCTURES

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

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

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

Time Complexity
Time Complexity is a way to represent the amount of time needed by the program to run to completion. We
will study this in details in our section. Similarly it can be based on
Number of inputs
Number of outputs
Type of selecting statement
Asymptotic analysis:
The definition of asymptotic is a line that approaches a curve but never touches. A curve and a line that get closer
but do not intersect are examples of a curve and a line that are asymptotic to each other)
Asymptotic analysis of an algorithm refers to defining the mathematical boundation/framing of its run-
time performance. Using asymptotic analysis, we can very well conclude the best case, average case, and
worst case scenario of an algorithm.
Asymptotic analysis is input bound i.e., if there's no input to the algorithm, it is concluded to work in a
constant time. Other than the "input" all other factors are considered constant.
Asymptotic analysis refers to computing the running time of any operation in mathematical units of
computation.
For example, the running time of one operation is computed as f(n) and may be for another operation it is
computed as g(n2). This means the first operation running time will increase linearly with the increase
in n and the running time of the second operation will increase exponentially when n increases. Similarly,
the running time of both operations will be nearly the same if n is significantly small.
Usually, the time required by an algorithm falls under three types
Best Case Minimum time required for program execution.
Average Case Average time required for program execution.
Worst Case Maximum time required for program execution.

Asymptotic Notations:

Following are the commonly used asymptotic notations to calculate the running time complexity of an algorithm.

Notation

Notation

Notation
Big Oh Notation, ():
The notation (n) is the formal way to express the upper bound of an algorithm's running time. It measures the
worst case time complexity or the longest amount of time an algorithm can possibly take to complete.

Bit Institute Of Technology, Hindupur. Page 2


DATA STRUCTURES

For example, for a function f(n)

(f(n)) = { g(n) : there exists c > 0 and n0 such that f(n) c.g(n) for all n > n0. }

Omega Notation, ():


The notation (n) is the formal way to express the lower bound of an algorithm's running time. It measures the best
case time complexity or the best amount of time an algorithm can possibly take to complete.

For example, for a function f(n)


(f(n)) { g(n) : there exists c > 0 and n0 such that g(n) c.f(n) for all n > n0. }

Theta Notation, ():


The notation (n) is the formal way to express both the lower bound and the upper bound of an algorithm's running
time. It is represented as follows

(f(n)) = { g(n) if and only if g(n) = (f(n)) and g(n) = (f(n)) for all n > n0. }

Bit Institute Of Technology, Hindupur. Page 3


DATA STRUCTURES

Introduction to Data Structures:

DATA STRUCTURE:
Data Structure is a way of collecting and organizing data in such a way that we can perform
operations on these data in an effective way. Data Structures is about rendering data elements in terms of
some relationship, for better organization and storage.
Example:
For example, we have data player's name "sachin" and age 26. Here "sachin" is of String data
type and 26 are of integer data type. Similarly for organizing data will be look lik student name, age, roll
no, address and other details.
We can organize this data as a record like Player record. Now we can collect and store player's records in a
file or database as a data structure. For example: "Dhoni" 30, "Gambhir" 31, "Sehwag" 33
In simple language, Data Structures are structures programmed to store ordered data, so that various
operations can be performed on it easily.
Algorithm + data
(Or)
structure=program
A data structure is a specialized format for organizing and storing data. So that we can easily access and
retrieve data in appropriate manner.
General data structure types include the array, the file, the record, the table, the tree, and so on.
Any data structure is designed to organize data to suit a specific purpose so that it can be accessed and
worked with in appropriate ways.

DATA STRUCTURES ARE IMPORTANT FOR THE FOLLOWING REASONS:

Data structures are used in almost every program or software system


Specific data structures are essential ingredients of many efficient algorithms, and make possible the
management of huge amounts of data, such as large integrated collection of databases.

Some programming languages emphasize(importance) data structures rather than algorithms, as the key
organizing factor in software design.

DATA STRUCTURES CLASSIFICATION:

Data structures can be classified into 2 ways. The following are to be


1. Linear data structures
2. Non-linear data structures
Linear data structures
Linear data structures organize their data elements in a linear fashion, where data elements are attached one
after the other.
Data elements in a liner data structure are traversed one after the other and only one element can be
directly reached while traversing.
Linear data structures are very easy to implement, since the memory of the computer is also organized in a
linear fashion.
Some commonly used linear data structures are arrays, linked lists, stacks and queues.
An arrays is a collection of data elements where each element could be identified using an index.
A linked list is a sequence of nodes, where each node is made up of a data element and a reference to the
next node in the sequence.
A stack is actually a list where data elements can only be added or removed from the top of the list.
A queue is also a list, where data elements can be added from one end of the list and removed from the
other end of the list.
Nonlinear data structures
In nonlinear data structures, data elements are not organized in a sequential fashion.

Bit Institute Of Technology, Hindupur. Page 4


DATA STRUCTURES

A data item in a nonlinear data structure could be attached to several other data elements to reflect a special
relationship among them and all the data items cannot be traversed in a single run.
Data structures like trees and graphs and tables are some examples of widely used nonlinear data structures.
A tree is a data structure that is made up of a set of linked nodes, which can be used to represent a
hierarchical relationship among data elements.
A graph is a data structure that is made up of a finite set of edges and vertices. Edges represent connections
or relationships among vertices that stores data elements.
Table means combination of rows and columns collected together.
Difference between Linear and Nonlinear Data Structures
Main difference between linear and nonlinear data structures lie in the way they organize data elements.
In linear data structures, data elements are organized sequentially and therefore they are easy to implement
in the computers memory. In nonlinear data structures, a data element can be attached to several other data
elements to represent specific relationships that exist among them.
Due to this nonlinear structure, they might be difficult to be implemented in computers linear memory
compared to implementing linear data structures.

Data structures

Linear Data structures Non-linear Data structures

Trees Graphs Tables


Array Stack Queue Linked list

Basic Operations of data structures:


The data in the data structures are processed by certain operations. The particular data
structure chosen largely depends on the frequency of the operation that needs to be performed
on the data structure.

Traversing

o Searching

Insertion

Deletion

Sorting

Merging

Bit Institute Of Technology, Hindupur. Page 5


DATA STRUCTURES

Arrays:

Why?
In some cases it is necessary to deal or use many variables so for that we are using the concept of arrays.
We can write the program by considering minimum number of variables but when we want to use multiple variables
if we declare that variables individually program complexity increases to overcome that we are preferring arrays

Definition:
An array is a collection of data items, all of the same type, accessed using a common name. array index starts
from 0(zero) onwards
or
Arrays a kind of data structure that can store a fixed-size sequential collection of elements of the same type. An
array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables
of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array
variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A
specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the
highest address to the last element.

Declaring Array:

Syntax:
Data type array name [subscript];
Another name for subscript can be called with index also.
Where data type------- indicates type of data
Array name indicates name of an array to identify
Subscript indicates size of an array.
Example:
int a[5];
This is called one dimensional array where data type is int, array name is a and subscript is 5 which it means the can able to store 5 elements.

Array initialization:
Assigning values before processing can be known Arrays. Initialization can be classified into 4 ways. The following
are to be
1. Complete initialization
2. Partial initialization
3. Initialization without size
4.String initialization
Complete initialization:
The process of assigning values completely according to or based on size of an array can be known as
complete initialization.
You can initialize an array in C either one by one or using a single statement as follows
Syntax:
Data type array name [index]={value1,value2,value3,.valuen};

Bit Institute Of Technology, Hindupur. Page 6


DATA STRUCTURES
Example:
int bit [5] = {10,20,30,40,50};
Which means bit [0] = 10, bit [1] = 20, bit [2] = 30, bit [3] = 40, bit [4] = 50.

bit[0] bit[1] bit[2] bit[3] bit[4] array names

values

1001 1003 1005 1007 1009 address

Here data type is integer so it occupies two (2) bytes for each and every location.

Partial initialization:

The process of assigning values partially according to or based on size of an array can be known as
complete initialization.
In other words 10 20 30 40 50 we are not
going to assign values in
complete manner.
You can initialize an array in C either one by one or using a single statement as follows
Syntax:
Data type array name [index]={value1,value2,value3,.value n};
Example:
int bit [5] = {10,20,30};

Which means bit [0] = 10, bit [1] = 20, bit [2] = 30

Here we assigned only 3 values but actual size of an array is or it can able to store five elements but
instead we only assigned 3 values. This type of initial can be known as Partial initialization.

Initialization without size:


The process of assigning values partially according to or based on size of an array can be known as
complete initialization. In other words we are not going to assign values in complete manner.
You can initialize an array in C either one by one or using a single statement as follows
Syntax:
Data type array name [ ] = {value1, value2, value3,.value n};
Example:
int bit [] = {10,20,30,40,50,60};

Which means bit [0] = 10, bit [1] = 20, bit [2] = 30, bit [3] = 40, bit [4] = 50, bit [5] = 60
Here we assigned only 6 values but actual size of an array not defined so according to user requirement we
may also assign vales and memory will be allocated whatever the values entered by user. This type of initialization
can be known as initialization without size.

Types of an array:
There are 2 types of C arrays. They are,
1. One dimensional array
2. Multi dimensional array
Two dimensional array
N dimensional array and so on

Bit Institute Of Technology, Hindupur. Page 7


DATA STRUCTURES

Single Dimensional Array:

1. Single or One Dimensional array is used to represent and store data in a linear form.

2. Array having only one subscript variable is called One-Dimensional array

3. It is also called as Single Dimensional Array or Linear Array

Syntax:

<Data-type> <array name> [size];

Example of Single Dimensional Array:

int ia[3] = {2, 3, 4}; and

char car[20] = "bit college" ; and float far[3] = {12.5,13.5,14.5} ;

Multi Dimensional Array:

Syntax:
Data type array name [subscript1] [subscript2];;
Where data type------- indicates type of data
Array name indicates name of an array to identify
Subscript 1 indicates number of rows, Subscript 2 indicates number of columns

1. Array having more than one variable is called Multi-Dimensional array.

2. Multi Dimensional Array is also called as Matrix.

Example: Two Dimensional Array

int a[3][3] = { 1,2,3


5,6,7
8,9,0 };

EXAMPLE PROGRAM FOR ONE DIMENSIONAL ARRAY IN C:


#include<stdio.h>

int main()
{
int i;
int arr[5] = {10,20,30,40,50};

// declaring and Initializing array in C

Bit Institute Of Technology, Hindupur. Page 8


DATA STRUCTURES
//To initialize all array elements to 0, use int arr[5]={0};
/* Above array can be initialized as below also
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50; */

for (i=0;i<5;i++)
{
// Accessing each variable
printf("value of arr[%d] is %d \n", i, arr[i]);
}

}
Output:
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50.

EXAMPLE PROGRAM FOR TWO DIMENSIONAL ARRAY IN C:


#include<stdio.h>

int main()
{
int i,j;
// declaring and Initializing array
int arr[2][2] = {10,20,30,40};
/* Above array can be initialized as below also
arr[0][0] = 10; // Initializing array
arr[0][1] = 20;
arr[1][0] = 30;
arr[1][1] = 40; */
for (i=0;i<2;i++)
{
for (j=0;j<2;j++)
{
// Accessing variables
printf("value of arr[%d] [%d] : %d\n",i,j,arr[i][j]);
}
}
}
Output:
value of arr[0] [0] is 10
value of arr[0] [1] is 20
value of arr[1] [0] is 30
value of arr[1] [1] is 40

Linked list basics:


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

Bit Institute Of Technology, Hindupur. Page 9


DATA STRUCTURES

Advantages of Linked Lists

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

Insertion and deletion operations can be easily implemented.

Stacks and queues can be easily executed.

Linked List reduces the access time.

Disadvantages of Linked Lists

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

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

Reverse Traversing is difficult in linked list.

Types of Linked Lists

Singly Linked List:

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

Doubly Linked List:

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

Bit Institute Of Technology, Hindupur. Page 10


DATA STRUCTURES

Circular Linked List:

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

Index of linked list

Introduction to Linked List

1. Introduction to Linked List

2. Advantages of Linked List

3. Disadvantages of Linked List

4. Array vs Linked-List

Types

1. Singly Linked List

2. Doubly Linked List

3. Circular Linked List

Singly Linked List Operations

Create Linked List

Bit Institute Of Technology, Hindupur. Page 11


DATA STRUCTURES

Traversing through Singly Linked List (SLL)

Display Elements

Counting Number of Nodes or length of linked list

Searching Particular node in SLL

Inserting Element at Front

Inserting Element at End

Inserting Element at Middle

Delete First Elements

Delete Middle Elements

Delete Last Elements

Introduction to Linked Lists:

We are learning this topic using c programming. Linked list is a type of data structure provided in C
language to make use of pointer efficiently.

Introduction to Linked List

1. It is a data Structure which consists if group of nodes that forms a sequence.

2. It is very common data structure that is used to create tree, graph and other abstract data types.

Linked list comprise of group or list of nodes in which each node have link to next node to form a chain

Linked List definition

1. Linked List is Series of Nodes

2. Each node Consist of two Parts Data Part & Pointer Part

3. Data part can be used for storing the value

Bit Institute Of Technology, Hindupur. Page 12


DATA STRUCTURES
4. Pointer Part stores the address of the next node

What is linked list Node ?

1. Each Linked List Consists of Series of Nodes

2. In above Diagram , Linked List Consists of three nodes A,B,C etc

3. Node A has two part one data part which consists of the 5 as data and the second part which contain the
address of the next node (i.e it contain the address of the next node)

Linked list Blocks:

Linked list is created using following elements

No Element Explanation

1 Node Linked list is collection of number of nodes

2 Address Field in Node Address field in node is used to keep address of next node

3 Data Field in Node Data field in node is used to hold data inside linked list.

We can represent linked list in real life using train in which all the buggies are nodes and two
coaches are connected using the connectors.

Bit Institute Of Technology, Hindupur. Page 13


DATA STRUCTURES
Main node (like engine) data inside node (people) address node (provide connection between two)

Last node not connected any further node so last node


indicates with zero (0).

In case of railway we have peoples seating arrangement inside the coaches is called as data part of lined list
while connection between two buggies is address filed of linked list.
Like linked list, trains also have last coach which is not further connected to any of the buggie. Engine can
be called as first node of linked list
Linked List of advantages:

1. Linked List is Dynamic data Structure.

2. Linked List can grow and shrink during run time.

3. Insertion and Deletion Operations are Easier

4. Efficient Memory Utilization Faster Access time,

5. Linear Data Structures such as Stack, Queue can be easily implemented using Linked list

Disadvantages/drawbacks of linked list:

1. Wastage of memory

2. No random access

3. Time consuming

4. Heap space restriction

5. Reverse traversing is difficult

Singly Linked List:


1. In this type of Linked List two successive nodes are linked together in linear fashion.

2. Each Node contains address of the next node to be followed.

3. In Singly Linked List only Linear or Forward Sequential movement is possible.

4. Elements are accessed sequentially, no direct access is allowed.

Explanation:
1. It is most basic type of Linked List in C.

Bit Institute Of Technology, Hindupur. Page 14


DATA STRUCTURES
2. It is simple sequence of dynamically allocated Nodes.

3. Each Node has its successor and predecessor.

4. First Node does not have predecessor while last node does not have any successor.

5. Last Node have successor reference as NULL.

6. In the above Linked List We have 3 types of nodes.(first, middle, last nodes)

7. In Singly Linked List access is given only in one direction thus Accessing Singly Linked is
Unidirectional.

8. We can have multiple data fields inside Node but we have only single Link for next node.

Node Structure for Singly Linked List :


struct node {
int data;
struct node *next;
}start = NULL;

In the above node structure we have defined two fields in structure

No Field Significance

1 data It is Integer Part for Storing data inside Linked List Node

It is pointer field which stores the address of another structure


2 next
(i.e. node)

Explanation of Node Structure:


1. We have declared structure of type NODE, i.e we have created a Single Linked List Node.

Bit Institute Of Technology, Hindupur. Page 15


DATA STRUCTURES
2. A Node in general language is a Structure having two value containers i.e [Square box having two
Partitions]

3. One value container stores actual data and another stores address of the another structure i.e
(Square box having two partitions)

4. We have declared a structure and also created 1 very first structure called Start.

5. Very first node Start contain 1 field for storing data and another field for address of another structure

6. As this is very first node or Structure, we have specified its next field with NULL value.
NULL means NOTHING , if next node is unavailable then initialize variable name to NULL.

Operations on single linked list:


In the previous chapter we have studied Node structure of singly linked list. In this chapter we will be
looking into creation of singly linked list.

C Program to Create Singly Linked List :

void creat()
{
char ch;
do
{
struct node *new_node,*current;
new_node=(struct node *)malloc(sizeof(struct node));

printf("nEnter the data : ");


scanf("%d",&new_node->data);
new_node->next=NULL;

if(start==NULL)
{
start=new_node;
current=new_node;
}
else
{
current->next=new_node;
current=new_node;
}
printf("nDo you want to creat another : ");
ch=getche();
}while(ch!='n');
}

Step 1 : Include Alloc.h Header File


1. We dont know, how many nodes user is going to create once he execute the program.

Bit Institute Of Technology, Hindupur. Page 16


DATA STRUCTURES
2. In this case we are going to allocate memory using Dynamic Memory Allocation functions such as
Alloc & Malloc.

3. Dynamic memory allocation functions are included in alloc.h


#include<alloc.h>

Step 2 : Define Node Structure


We are now defining the new global node which can be accessible through any of the function.
struct node {
int data;
struct node *next;
}*start=NULL;

Step 3 : Create Node using Dynamic Memory Allocation


Now we are creating one node dynamically using malloc function.We dont have prior knowledge
about number of nodes , so we are calling malloc function to create node at run time.
new_node=(struct node *)malloc(sizeof(struct node));

Step 5 : Fill Information in newly Created Node


Now we are accepting value from the user using scanf. Accepted Integer value is stored in the data
field.
[box]Tip #1 Whenever we create new node , Make its Next Field as NULL.[/box]
printf("nEnter the data : ");
scanf("%d",&new_node->data);
new_node->next=NULL;

Bit Institute Of Technology, Hindupur. Page 17


DATA STRUCTURES

Step 6 : Creating Very First Node


If node created in the above step is very first node then we need to assign it as Starting node. If start is
equal to null then we can identify node as first node
start == NULL

First node has 3 names : new_node,current,start


if(start == NULL) { {
start = new_node;
curr = new_node;
}

Step 7 : Creating Second or nth node


1. Lets assume we have 1 node already created i.e we have first node. First node can be referred as
new_node,curr,start.

2. Now we have called create() function again


Now we already have starting node so control will be in the else block
else
{
current->next = new_node;
current = new_node;
}

Inside Else following things will happen


In the else block we are making link between new_node and current node.

Bit Institute Of Technology, Hindupur. Page 18


DATA STRUCTURES

current->next = new_node;

Now move current pointer to next node


current = new_node;

Traversing through Singly Linked List (SLL):


In the previous chapter we have learnt about the Creation of Singly Linked List. In this chapter, we will see
how to traverse through Singly Linked List using C Programming.

1. Introduction:
Consider the Singly Linked list node structure. Traversing linked list means visiting each and every node of the
singly linked list. Following steps are involved while traversing the singly linked list

1. Firstly move to the first node

2. Fetch the data from the node and perform the operations such as arithmetic operation or any operation
depending on data type.

3. After performing operation, advance pointer to next node and perform all above steps on Visited node.

2. Node Structure and Program Declaration:


struct node {
int data;
struct node *next;
}*start=NULL;

and the function definition for traversing linked list is


struct node *temp = start; //Move to First Node

do {

Bit Institute Of Technology, Hindupur. Page 19


DATA STRUCTURES

// Do Your Operation
// Statement ...1
// Statement ...2
// Statement ...3
// Statement ...n

temp = temp->next; //Move Pointer to Next Node

}while(temp!=NULL);

3. Explanation of Traversing Linked List :


We know that, In order to traverse linked list, We need to visit first node and then visiting nodes one by one
until the last node is reached.
temp = start; //Move to First Node
do {
// Do Your Operation
// Statement ...1
// Statement ...2
// Statement ...3
// Statement ...n
temp = temp->next; //Move Pointer to Next Node

}while(temp!=NULL);

Explanation:

Initially
temp = start;

1. Store Address of Starting node into temp, print data stored in the node temp. ## Refer : Different
Syntax and Terms in Linked List

2. Once Data stored in the temp is printed, move pointer to the next location so that temp will contain
address of 2nd node.
[box]

Special Note:
In Singly Linked List Program, do not change start index un-necessarily because we must have something that
can store address of Head node.

Display Singly Linked List from First to Last


In the last chapter we have learnt about traversing the linked list. In this chapter we will be printing the
content of the linked list from start to last.

Bit Institute Of Technology, Hindupur. Page 20


DATA STRUCTURES

Steps for Displaying the Linked List:


1. In order to write the program for display, we must create a linked list using create (). Then and then
only we can traverse through the linked list.

2. Traversal Starts from Very First node. We cannot modify the address stored inside global variable
start thus we have to declare one temporary variable -temp of type node.

3. In order to traverse from start to end you should assign Address of Starting node in Pointer
variable i.e temp
struct node *temp; //Declare temp
temp = start; //Assign Starting Address to temp

Now we are checking the value of pointer (i.e temp). If the temp is NULL then we can say that last node is
reached.
while(temp!=NULL)
{
printf("%d",temp->data);
temp=temp->next;
}

See below dry run to understand the complete code and consider the linked list shown in the above figure

Control Position Printed Value temp points to

Before Going into Loop - Starting Node

Iteration 1 1 Node with data = 3

Iteration 2 3 Node with data = 5

Iteration 3 5 Node with data = 7

Iteration 4 7 NULL

Iteration 5(False Condition) - -

Complete Display Function :


void display()
{
struct node *temp;
temp=start;
while(temp!=NULL)
{
printf("%d",temp->data);
temp=temp->next;
}
}

Bit Institute Of Technology, Hindupur. Page 21


DATA STRUCTURES

Some Terminology of Linked List:


Consider the following node structure
struct node {
int data;
struct node *next;
}*start = NULL;
struct node *new_node,*current;

Summary of Different Linked List Terms:


Declaration Term Explanation

struct node
Explanation
Declaring Variable of Type Node.
*new_node,*current; of Terms :
Declared a global variable of type node. start is used to refer the
*start = NULL;
starting node of the linked list.

Access the 2nd Node of the linked list. This term contain the
start->next address of 2nd node in the linked list. If 2nd node is not present
then it will return NULL.

start->data It will access data field of starting node.

start->next->data It will access the data field of 2nd node.

Variable current will contain the address of 2nd node of the


current = start->next
linked list.

After the execution of this statement, 2nd node of the linked list will
start = start->next;
be called as starting node of the linked list.

Consider the above linked list , we have initial conditions

Bit Institute Of Technology, Hindupur. Page 22


DATA STRUCTURES
1. start node is pointing to First Node [ data = 1 ]

2. current node is pointing to Second Node [ data = 3 ]


with respect to the above linked list , data will be
Term Explanation

current = start->next current will point to node having data = 3

int num = start->data num will contain integer value 1.

int num = start->next->data num will contain integer value 3.

temp = current->next temp will point to node having data = 5

int num = current->data num will contain integer value 3.

int num = current->next->data num will contain integer value 5.

Insert node at Start/First Position in Singly Linked List

Inserting node at start in the SLL (Steps):

1. Create New Node

2. Fill Data into Data Field

3. Make its Pointer or Next Field as NULL

4. Attach This newly Created node to Start

5. Make newnode as Starting node


void insert_at_beg()
{
struct node *new_node,*current;

new_node=(struct node *)malloc(sizeof(struct node));

if(new_node == NULL)
printf("nFailed to Allocate Memory");

printf("nEnter the data : ");


scanf("%d",&new_node->data);
new_node->next=NULL;

Bit Institute Of Technology, Hindupur. Page 23


DATA STRUCTURES

if(start==NULL)
{
start=new_node;
current=new_node;
}
else
{
new_node->next=start;
start=new_node;
}
}

Diagram :

Attention :

1. If starting node is not available then Start = NULL then following part is executed
if(start==NULL)
{
start=new_node;
current=new_node;
}

2. If we have previously created First or starting node then else part will be executed to insert node at
start
else
{
new_node->next=start;
start=new_node;
}

Inserting node at start in the SLL (Steps):

1. Create New Node

Bit Institute Of Technology, Hindupur. Page 24


DATA STRUCTURES
2. Fill Data into Data Field

3. Make its Pointer or Next Field as NULL

4. Node is to be inserted at Last Position so we need to traverse SLL upto Last Node.

5. Make link between last node and newnode


void insert_at_end()
{
struct node *new_node,*current;

new_node=(struct node *)malloc(sizeof(struct node));

if(new_node == NULL)
printf("nFailed to Allocate Memory");

printf("nEnter the data : ");


scanf("%d",&new_node->data);
new_node->next=NULL;

if(start==NULL)
{
start=new_node;
current=new_node;
}
else
{
temp = start;
while(temp->next!=NULL)
{
temp = temp->next;
}
temp->next = new_node;
}
}

Insert node at Last / End Position in Singly Linked List:


Diagram:

Attention :

1. If starting node is not available then Start = NULL then following part is executed
if(start==NULL)
{
start=new_node;
current=new_node;
}

Bit Institute Of Technology, Hindupur. Page 25


DATA STRUCTURES
2. If we have previously created First or starting node then else part will be executed to insert node at
start

3. Traverse Upto Last Node., So that temp can keep track of Last node
else
{
temp = start;
while(temp->next!=NULL)
{
temp = temp->next;
}

4. Make Link between Newly Created node and Last node ( temp )
temp->next = new_node;

To pass Node Variable to Function Write it as


void insert_at_end(struct node *temp)

Linked-List : Insert Node at Middle Position in Singly Linked List


void insert_mid()
{
int pos,i;
struct node *new_node,*current,*temp,*temp1;

new_node=(struct node *)malloc(sizeof(struct node));

printf("nEnter the data : ");


scanf("%d",&new_node->data);

new_node->next=NULL;
st :
printf("nEnter the position : ");
scanf("%d",&pos);

if(pos>=(length()+1))
{
printf("nError : pos > length ");
goto st;
}

if(start==NULL)
{
start=new_node;
current=new_node;
}
else
{
temp = start;
for(i=1;i< pos-1;i++)
{
temp = temp->next;
}
temp1=temp->next;
temp->next = new_node;
new_node->next=temp1;

Bit Institute Of Technology, Hindupur. Page 26


DATA STRUCTURES

}
}

Explanation :
Step 1 : Get Current Position Of temp and temp1 Pointer.
temp = start;
for(i=1;i< pos-1;i++)
{
temp = temp->next;
}

Step 2 :
temp1=temp->next;

Step 3 :
temp->next = new_node;

Step 4 :

Bit Institute Of Technology, Hindupur. Page 27


DATA STRUCTURES

new_node->next = temp1

Program :

void del_beg()
{
struct node *temp;

temp = start;
start = start->next;

free(temp);
printf("nThe Element deleted Successfully ");
}

Attention:
Step 1: Store Current Start in another Temporary Pointer
temp = start;

Step 2: Move Start Pointer One position ahead


start = start->next;

Bit Institute Of Technology, Hindupur. Page 28


DATA STRUCTURES

Step 3 : Delete temp i.e Previous Starting Node as we have Updated Version of Start Pointer
free(temp);

Searching of a node:.

If data or element is not present then return starting node

Otherwise return the exact node.


struct node * search(int num)
{
int flag = 0;
struct node *temp;

temp = start;

while(temp!=NULL)
{
if(temp->data == num)
return(temp); //Found
temp = temp->next;
}

if(flag == 0)
return(start); // Not found
}

Counting number of Nodes in Linked List:

We know the logic for traversing through the linked list in C Programming.
Function for counting the singly linked nodes is very similar to display (), only difference is that
instead of printing data we are incrementing length variable.
Void count ()

Bit Institute Of Technology, Hindupur. Page 29


DATA STRUCTURES

{
struct node *temp;
int length = 0;
temp = start;
while(temp!=NULL)
{
length++;
temp=temp->next;
}
printf("nLength of Linked List : %d",length);
}

Program to Create Singly Linked List .

More Detailed Step By Step Explanation


//Program by :- Pritesh A Taral
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
//-------------------------------------------------
struct node
{
int data;
struct node *next;
}*start=NULL;
//------------------------------------------------------------

void creat()
{
char ch;
do
{
struct node *new_node,*current;

new_node=(struct node *)malloc(sizeof(struct node));

printf("nEnter the data : ");


scanf("%d",&new_node->data);
new_node->next=NULL;

if(start==NULL)
{
start=new_node;
current=new_node;
}
else
{
current->next=new_node;
current=new_node;
}

printf("nDo you want to creat another : ");


ch=getche();
}while(ch!='n');
}
//------------------------------------------------------------------

Bit Institute Of Technology, Hindupur. Page 30


DATA STRUCTURES

void display()
{
struct node *new_node;
printf("The Linked List : n");
new_node=start;
while(new_node!=NULL)
{
printf("%d--->",new_node->data);
new_node=new_node->next;
}
printf("NULL");
}
//----------------------------------------------------
void main()
{
create();
display();
}
//----------------------------------------------------

Output :
Enter the data : 10
Do you want to creat another : y
Enter the data : 20
Do you want to creat another : y

Enter the data : 30


Do you want to creat another : n

The Linked List :


10--->20--->30--->NULL

Doubly Linked List: Traverse Bi-directional:


1. In Doubly Linked List , each node contain two address fields .

2. One address field for storing address of next node to be followed and second address field contain
address of previous node linked to it.

3. So Two way access is possible i.e We can start accessing nodes from start as well as from last .

4. Like Singly Linked List also only Linear but Bidirectional Sequential movement is possible.

5. Elements are accessed sequentially , no direct access is allowed.

Bit Institute Of Technology, Hindupur. Page 31


DATA STRUCTURES

Explanation:
1. Doubly Linked List is most useful type of Linked List.

2. In DLL we have facility to access both next as well as previous data using next link and previous
link.

3. In the above diagram , suppose we are currently on 2nd node i.e at 4 then we can access next and
previous data using
To Access Next Data : curr_node->next->data
To Access Previous Data : curr_node->previous->data

4. We have to always maintain start node, because it is the only node that is used to keep track of
complete linked list.

Program for double linked list:


#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct node {
int data;
int key;

struct node *next;


struct node *prev;
};

//this link always point to first Link


struct node *head = NULL;

//this link always point to last Link


struct node *last = NULL;

struct node *current = NULL;

//is list empty


bool isEmpty() {
return head == NULL;
}

int length() {
int length = 0;
struct node *current;

for(current = head; current != NULL; current = current->next){


length++;
}

return length;

Bit Institute Of Technology, Hindupur. Page 32


DATA STRUCTURES
}

//display the list in from first to last


void displayForward() {

//start from the beginning


struct node *ptr = head;

//navigate till the end of the list


printf("\n[ ");

while(ptr != NULL) {
printf("(%d,%d) ",ptr->key,ptr->data);
ptr = ptr->next;
}

printf(" ]");
}

//display the list from last to first


void displayBackward() {

//start from the last


struct node *ptr = last;

//navigate till the start of the list


printf("\n[ ");

while(ptr != NULL) {

//print data
printf("(%d,%d) ",ptr->key,ptr->data);

//move to next item


ptr = ptr ->prev;
printf(" ");
}

printf(" ]");
}

//insert link at the first location


void insertFirst(int key, int data) {

//create a link
struct node *link = (struct node*) malloc(sizeof(struct node));
link->key = key;
link->data = data;

if(isEmpty()) {
//make it the last link
last = link;

Bit Institute Of Technology, Hindupur. Page 33


DATA STRUCTURES
} else {
//update first prev link
head->prev = link;
}

//point it to old first link


link->next = head;

//point first to new first link


head = link;
}

//insert link at the last location


void insertLast(int key, int data) {

//create a link
struct node *link = (struct node*) malloc(sizeof(struct node));
link->key = key;
link->data = data;

if(isEmpty()) {
//make it the last link
last = link;
} else {
//make link a new last link
last->next = link;

//mark old last node as prev of new link


link->prev = last;
}

//point last to new last node


last = link;
}

//delete first item


struct node* deleteFirst() {

//save reference to first link


struct node *tempLink = head;

//if only one link


if(head->next == NULL){
last = NULL;
} else {
head->next->prev = NULL;
}

head = head->next;
//return the deleted link
return tempLink;
}

Bit Institute Of Technology, Hindupur. Page 34


DATA STRUCTURES
//delete link at the last location

struct node* deleteLast() {


//save reference to last link
struct node *tempLink = last;

//if only one link


if(head->next == NULL) {
head = NULL;
} else {
last->prev->next = NULL;
}

last = last->prev;

//return the deleted link


return tempLink;
}
Void main() {
insertFirst(1,10);
insertFirst(2,20);
insertFirst(3,30);
insertFirst(4,1);
insertFirst(5,40);
insertFirst(6,56);

printf("\nList (First to Last): ");


displayForward();

printf("\n");
printf("\nList (Last to first): ");
displayBackward();

printf("\nList , after deleting first record: ");


deleteFirst();
displayForward();

printf("\nList , after deleting last record: ");


deleteLast();
displayForward();

Output:
List (First to Last):
[ (6,56) (5,40) (4,1) (3,30) (2,20) (1,10) ]

List (Last to first):


[ (1,10) (2,20) (3,30) (4,1) (5,40) (6,56) ]
List , after deleting first record:
[ (5,40) (4,1) (3,30) (2,20) (1,10) ]
List , after deleting last record:
[ (5,40) (4,1) (3,30) (2,20) ]

Bit Institute Of Technology, Hindupur. Page 35


DATA STRUCTURES
Circular Linked List

1. Circular Linked List is Divided into 2 Categories .

o Singly Circular Linked List

o Doubly Circular Linked List

2. In Circular Linked List Address field of Last node contain address of First Node.

3. In short First Node and Last Nodes are adjacent .

4. Linked List is made circular by linking first and last node , so it looks like circular chain [ shown in
Following diagram ].

5. Two way access is possible only if we are using Doubly Circular Linked List

6. Sequential movement is possible

7. No direct access is allowed.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>

struct node {
int data;
int key;

struct node *next;


};

struct node *head = NULL;


struct node *current = NULL;

bool isEmpty() {
return head == NULL;
}

int length() {
int length = 0;

Bit Institute Of Technology, Hindupur. Page 36


DATA STRUCTURES
//if list is empty
if(head == NULL) {
return 0;
}

current = head->next;

while(current != head) {
length++;
current = current->next;
}

return length;
}

//insert link at the first location


void insertFirst(int key, int data) {

//create a link
struct node *link = (struct node*) malloc(sizeof(struct node));
link->key = key;
link->data = data;

if (isEmpty()) {
head = link;
head->next = head;
} else {
//point it to old first node
link->next = head;

//point first to new first node


head = link;
}
}

//delete first item


struct node * deleteFirst() {

//save reference to first link


struct node *tempLink = head;

if(head->next == head) {
head = NULL;
return tempLink;
}

//mark next to first link as first


head = head->next;

//return the deleted link


return tempLink;
}

Bit Institute Of Technology, Hindupur. Page 37


DATA STRUCTURES
//display the list
void printList() {

struct node *ptr = head;


printf("\n[ ");

//start from the beginning


if(head != NULL) {

while(ptr->next != ptr) {
printf("(%d,%d) ",ptr->key,ptr->data);
ptr = ptr->next;
}
}

printf(" ]");
}

main() {
insertFirst(1,10);
insertFirst(2,20);
insertFirst(3,30);
insertFirst(4,1);
insertFirst(5,40);
insertFirst(6,56);

printf("Original List: ");

//print list
printList();

while(!isEmpty()) {
struct node *temp = deleteFirst();
printf("\nDeleted value:");
printf("(%d,%d) ",temp->key,temp->data);
}

printf("\nList after deleting all items: ");


printList();
}

Output:
Original List:
[ (6,56) (5,40) (4,1) (3,30) (2,20) ]
Deleted value :(6,56)
Deleted value :(5,40)
Deleted value:(4,1)
Deleted value:(3,30)
Deleted value:(2,20)
Deleted value:(1,10)
List after deleting all items:
[ ]

Bit Institute Of Technology, Hindupur. Page 38


DATA STRUCTURES
Applications of Linked Lists

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

Linked lists can also be used to implement graphs

Undo functionality in Photoshop or word. Linked list of states

However, for any polynomial operation, such as addition or multiplication of polynomials , linked list
representation is more easier to deal with.

Linked lists are useful for dynamic memory allocation.

The real life application where the circular linked list is used is our Personal Computers, where multiple
applications are running.

All the running applications are kept in a circular linked list and the OS gives a fixed time slot to all for running.
The Operating System keeps on iterating over the linked list until all the applications are completed.

Sparse matrix representation

W Sparse matrix representation::hat is Sparse Matrix?


In computer programming, a matrix can be defined with a 2-dimensional array. Any array with 'm'
columns and 'n' rows represents a mXn matrix. There may be a situation in which a matrix contains more
number of ZERO values than NON-ZERO values. Such matrix is known as sparse matrix.

Sparse matrix is a matrix which contain Sparse matrix representation s very few non-zero elements.

When a sparse matrix is represented with 2-dimensional array, we waste lot of space to represent that
matrix.

For example, consider a matrix of size 100 X 100 containing only 10 non-zero elements. In this matrix,
only 10 spaces are filled with non-zero values and remaining spaces of matrix are filled with zero.

That means, totally we allocate 100 X 100 X 2 = 20000 bytes of space to store this integer matrix. And to
access these 10 non-zero elements we have to make scanning for 10000 times.

Bit Institute Of Technology, Hindupur. Page 39


DATA STRUCTURES
Sparse matrix representation:

Sparse Matrix Representations can be done in many ways following are two common representations:
1. Array representation
2. Linked list representation

Method 1: Using Arrays


2D array is used to represent a sparse matrix in which there are three rows named as
Row: Index of row, where non-zero element is located
Column: Index of column, where non-zero element is located
Value: Value of the non zero element located at index (row,column)

Method 2: Using Linked Lists


In linked list, each node has four fields. These four fields are defined as:
Row: Index of row, where non-zero element is located
Column: Index of column, where non-zero element is located
Value: Value of the non zero element located at index (row,column)
Next node: Address of the next node

Or

Bit Institute Of Technology, Hindupur. Page 40


DATA STRUCTURES

Bit Institute Of Technology, Hindupur. Page 41

Vous aimerez peut-être aussi