Sie sind auf Seite 1von 85

UNIT-1

Basic concepts- Algorithm Specification-Introduction,


Recursive algorithms, Data Abstraction, Performance
analysis- time complexity and space complexity, Asymptotic
Notation-Big O, Omega and Theta notations,
Introduction to Linear and Non Linear data structures-
Singly Linked Lists- Operations-Insertion, Deletion,
Concatenating singly linked lists, Circularly linked lists-
Operations for Circularly linked lists, Doubly Linked Lists-
Operations- Insertion, Deletion. Representation of single,
two dimensional arrays, sparse matrices-array and linked
1
ALGORITHM
Definition: An Algorithm is a method of representing the step-by-step
procedure for solving a problem. It is a method of finding the right answer to a
problem or to a different problem by breaking the problem into simple cases.

It must possess the following properties:

Finiteness: An algorithm should terminate in a finite number of steps.

Definiteness: Each step of the algorithm must be precisely (clearly) stated.

Effectiveness: Each step must be effective. i.e; it should be easily convertible


into program statement and can be performed exactly in a finite amount of
time.

Generality: Algorithm should be complete in itself, so that it can be used to


solve all problems of given type for any input data.

Input/Output: Each algorithm must take zero, one or more quantities as input
data and gives one of more output values.
2
Recursive Algorithms 1 of 10

Definition:
•A recursive algorithm is one in which objects are defined in terms
of other objects of the same type.

Advantages:
•Simplicity of code
•Easy to understand

Disadvantages:
•Memory
•Speed

3
Recursive Algorithms 2 of 10
All recursive algorithms must obey three important laws:

1.A recursive algorithm must have a base case.


2.A recursive algorithm must change its state and move
toward the base case.
3.A recursive algorithm must call itself, recursively

Types of Recursions:

1.Direct Recursion
2.Indirect Recursion
3.Tail Recursion
4.Linear Recursion
5.Tree Recursion

4
Recursive Algorithms 3 of 10
1. Direct Recursion
A C function is directly recursive if it contains
an explicit call to itself

Int foo (int x)


{
if ( x <= 0 ) return x;
return foo ( x – 1);
}

5
Recursive Algorithms 4 of 10

2. Indirect Recursion
A C function foo1 is indirectly recursive if it
contains a call to another function that
ultimately calls foo1.
int foo1(int x){ int foo2 (int y)
if (x <= 0) return x; {
return foo2 (x); return foo1(y – 1);
} }

6
Recursive Algorithms 5 of 10
3. Tail Recursion
A recursive function is said to be tail recursive if there is no pending operations performed on return from a recursive call

Tail recursive functions are often said to “return the value of the last recursive call as the value of the function”

Tail recursive factorial factorial is non-tail recursive

int fact_Trec (int n, int result) { int factorial (int n)


if (n == 1) return result; {
return fact_Trec (n – 1, n * result); if (n == 0) return 1;
} return n * factorial(n – 1);
}
factorial (int n) { Note: The “pending operation”
return fact_Trec (n, 1); (namely the multiplication) to be
} performed on return from each
recursive call 7
Recursive Algorithms 6 of 10

4. Linear Recursion
A recursive function is said to be linearly recursive
when no pending operation invokes another
recursive call to the function.

int factorial (int n)


{
if (n == 0) return 1;
return n * factorial ( n – 1);
}

8
Recursive Algorithms 7 of 10
5.Tree Recursion
A recursive function is said to be tree recursive (or
non-linearly recursive when the pending operation
does invoke another recursive call to the function.

The Fibonacci function fib provides a classic


example of tree
// Note recursion.
how the pending operation (the +)
// needs a 2nd recursive call to fib

int fib(int n)
{
if (n == 0) return 0;

if (n == 1) return 1;

return ( fib ( n – 1 ) + fib ( n – 2 ) );


}
9
Recursive Algorithms 8 of 10
Example1 : Factorial (Recursion)
Compute the factorial of integer n: The execution of a recursive algorithm
n! = 1 2 · · · n = uses a call stack to keep track of
( previous method call
1n=1
n (n − 1)! n > 1
algorithm factorial(n)
if n = 1 then
return 1 // base case of the recursion
else
return n factorial(n − 1) // recursive call

10
Recursive Algorithms 9 of 10
Example 2: Factorial (Tail-Recursion)
The previous factorial algorithm is augmented recursive, i.e. it
can be replaced by a tail-recursion

11
Recursive Algorithms 10 of 10
Example 3: Factorial (Iteration)
The tail-recursive factorial algorithm can be replaced by a simple
iterative loop

12
Data Abstraction
The basic data types includes char , int , float & double.
Some data types may be modified by keywords short , long ,
unsigned

Two mechanisms for grouping data together:


1.Arrays
2.Structures

Data types:

It is a collection of objects & set of operations that act on those


objects.
int consists of objects
{ 0 , +1 , -1 , +2 , -2 , INT_MAX, INT_MIN }
INT_MAX : largest integer on machine
INT_MIN: smallest integer on machine
It includes in <limits.h>

13
Data Abstraction
Abstract Data Type(ADT):

It is a data type i.e, organised in such a way that the specification of the
objects & the specification of the operations on the objects is separated
from the representation of the objects & implementation of the operations.

e.g : Ada have packages


C++ have class

The functions of a data types into several categories:


1.Creator / constructor
2.Transformers
3.Observers / reporters

14
Data Abstraction
1.Creator / constructor:

These functions create a new instance of the designed type.

2. Transformers :

These functions also create an instance of the designed


type generally by using 1 / more other instances.

3. Observers / reporters:

These functions provide information about an instance of


the type , but they do not change the instance

15
PERFORMANCE ANALYSIS 1 of 4
When several algorithms can be designed for the solution of a problem,
there arises the need to determine which among them is the best. The
efficiency of a program or an algorithm is measured by computing –

•Time Complexity

•Space Complexity

16
PERFORMANCE ANALYSIS 2 of 4

Time Complexity
•The time complexity of an algorithm is a function of the running time
of the algorithm.
•The time complexity is therefore given in terms of frequency count.
•Frequency count is basically a count denoting number of times of
execution of statement.

Example1:
1 Algorithm Message(n) 0
2 { 0
3 for i=1 to n do n+1
4 { 0
5 write(“Hello”); n
6 } 0
7 } 0
total frequency count 2n+1

While computing the time complexity we will neglect all the constants,
hence ignoring 2 and 1 we will get n. Hence the time complexity becomes
O(n).
17
PERFORMANCE ANALYSIS 3 of 4
Space Complexity

•The space complexity can be defined as amount of memory required by


an algorithm to run.

•To compute the space complexity we use two factors: constant and
instance characteristics. The space requirement S(p) can be given as

S(p) = C + Sp

where C is a constant i.e., fixed part and it denotes the space of inputs
and outputs. This space is an amount of space taken by instruction,
variables and identifiers.

Sp is a space dependent upon instance characteristics. This is a variable


part whose space requirement depend on particular problem instance.

18
PERFORMANCE ANALYSIS 4 of 4
Example:1
Algorithm add(a,b,c)
{
return a+b+c;
}
If we assume a, b, c occupy one word size then total size comes to be 3
S(p) = C (since C=3)

Example:2
Algorithm add(x,n)
{
sum=0.0;
for i= 1 to n do
sum:=sum+x[i];
return sum;
}
The n space required for x[], one space for n, one for i, and one for sum
S(p) ≥ (n+3)

19
Asymptotic Notations: 1 of 5

•To choose the best algorithm, we need to check efficiency of each


algorithm. The efficiency can be measured by computing time complexity
of each algorithm. Asymptotic notation is a shorthand way to represent
the time complexity.

•Using asymptotic notations we can give time complexity as “fastest


possible”, “slowest possible” or “average time”.

•Various notations such as Ω, θ, O used are called asymptotic notations.

20
Asymptotic Notations: 2 of 5
Big Oh Notation
Big Oh notation denoted by „O‟ is a method of representing the upper
bound of algorithm‟s running time. Using big oh notation we can give
longest amount of time taken by the algorithm to complete.
Definition:
Let, f(n) and g(n) are two non-negative functions. And if there exists an
integer n0 and constant C such that C > 0 and for all integers n > n0, f(n)
≤ c*g(n), then f(n) = Og(n).

Various meanings associated with big-oh are

O(1) constant computing time


O(n) linear
O(n2) quadratic
O(n3) cubic
O(2n) exponential
O(logn) logarithmic

The relationship among these computing time is


O(1)< O(logn)< O(n)< O(nlogn)< O(n2)< O(2n)
21
Asymptotic Notations: 3 of 5
Omega Notation
Omega notation denoted „Ω‟ is a method of representing the lower
bound of algorithm‟s running time. Using omega notation we can denote
shortest amount of time taken by algorithm to complete.

Definition:

Let, f(n) and g(n) are two non-negative functions. And if there exists an
integer n0 and constant C such that C > 0 and for all integers n > n0, f(n)
>c*g(n), then f(n) = Ω g(n).

22
Asymptotic Notations: 4 of 5
Theta Notation

Theta notation denoted as „θ‟ is a method of representing running time


between upper bound and lower bound.

Definition:

Let, f(n) and g(n) are two non-negative functions. There exists positive
constants C1 and C2 such that C1 g(n) ≤ f(n) ≤ C2 g(n) and f(n) = θ g(n)

23
Asymptotic Notations: 5 of 5
Best Case, Worst Case and Average Case Analysis

•If an algorithm takes minimum amount of time to run to completion for


a specific set of input then it is called best case complexity.

•If an algorithm takes maximum amount of time to run to completion for


a specific set of input then it is called worst case time complexity.

•The time complexity that we get for certain set of inputs is as a average
same. Then for corresponding input such a time complexity is called
average case time complexity.

24
Introduction to Linear & Non-linear
Data Structure 1 of 3
The data structure can be defined as the collection of elements and all
the possible operations which are required for those set of elements. In
other words data structure will tell us specific set of elements and
corresponding set of operations.

A data structure can be defined as a way of organizing and storing data


in a computer so that it can used efficiently.

Mathematically, a data structure D is a triplet, that is, D=(d, f, a) where

D= data structure
d= a set of variables (data objects)
f= a set of functions
a= set of rules to implement the functions.

25
Introduction to Linear & Non-linear
Data Structure 2 of 3
Data Structures:
A data structure is an arrangement of data in a computer's memory or even disk
storage.

It classified into two types


1. Linear Data Structures
2.Non Linear Data Structures

1. Linear Data Structures:


Linear data structures are those data structures in which data elements are
accessed (read and written) in sequential fashion ( one by one)

Eg: Stacks , Queues, Lists, Arrays

2. Non Linear Data Structures:


Non Linear Data Structures are those in which data elements are not accessed
in sequential fashion.

Eg: trees, graphs


26
Introduction to Linear & Non-linear
Data Structure 3 of 3
Types of Data Structure

Data Structure

Primitive Data Non Primitive


Structures Data Structures

Linear Data Non Linear Data


Eg: int, char, float
Structures Structures

Eg: array, linked


Eg: trees, graphs
list, stack, queue

27
Difference between linear and non linear
data structures
Linear DS Non Linear DS
Data elements are organized A data element can be
sequentially and therefore attached to several other
they are easy to implement data elements to represent
in the computer‟s memory. specific relationships that
exist among them. Due to
this nonlinear structure, they
might be difficult to be
implemented in computer‟s
linear memory compared to
implementing linear data
structures.

Every item is related to its Every item is attached with


previous and next time. many other items.
28
Difference between linear and non linear
data structures
Linear DS Non Linear DS
Data is arranged in linear Data is not arranged in sequence.
sequence.

Data items can be traversed in a Data cannot be traversed in a


single run. single run.

Eg. array, stcks, linked list, queue. Eg. tree, graph

Implementation is easy Implementation is difficult.


It contains data item and a single It contains a data item and two
link pointing to next element links left link pointing to
previous element and right link
pointing to next element
29
Difference between linear and non linear
data structures
Linear DS Non Linear DS
Syntax Syntax
Struct node Struct node
{ {
int data; int data;
struct node*link; struct node*left;
}; struct node*right;
};

30
SINGLY LINKED LIST 1 of 14
Definition of linked list

A linked list is a linear collection of homogeneous data


elements, called nodes, where linear order is maintained by
means of links or pointers.

Each node has two parts:


The first part contains the data (information of the element)
and
The second part contains the address of the next node (link
/next pointer field) in the list.

Data part of the link can be an integer, a character, a String or


an object of any kind.

31
SINGLY LINKED LIST 2 of 14
node
NODE
link struct Node
{
int data;
struct Node *link;
};
data

LINKED LIST

Start Null

A B C D
32
SINGLY LINKED LIST 3 of 14

Linear collection of self-referential structures, called nodes,


connected by pointer links.

Accessed via a pointer to the first node of the list.

Subsequent nodes are accessed via the link-pointer member stored


in each node.

Link pointer in the last node is set to null to mark the end of the
list.

Data stored dynamically – each node is created as necessary.

Length of a list can increase or decrease.

Becomes full only when the system has insufficient memory to


satisfy dynamic storage allocation requests.

33
SINGLY LINKED LIST 4 of 14

TYPES OF LINKED LISTS

1. Singly linked list


Begins with a pointer to the first node
Terminates with a null pointer
Only traversed in one direction

2. Circular, singly linked list


Pointer in the last node points back to the first node

3. Doubly linked list


Two “start pointers”- first element and last element
Each node has a forward pointer and a backward pointer
Allows traversals both forwards and backwards

4. Circular, doubly linked list


Forward pointer of the last node points to the first node
and backward pointer of the first node points to the last
node
34
SINGLY LINKED LIST 5 of 14

A singly linked list, or simply a linked list, is a linear collection of


data items. The linear order is given by means of POINTERS.
These types of lists are often referred to as linear linked list.

•Each item in the list is called a node.

•Each node of the list has two fields:

Information- contains the item being stored in the list.


Next address- contains the address to the next item in the list.

•The last node in the list contains NULL pointer to indicate that it
is the end of the list.

35
SINGLY LINKED LIST 6 of 14

OPERATIONS

Creation of a node
Insertions
Deletions
Traversing the list

Structure of a node: data link

struct node
{
int data;
struct node *next;
};

36
SINGLY LINKED LIST 7 of 14

CREATION OF A NODE:

Inittially first=NULL last=NULL

struct node *cur;

cur=(struct node*)malloc(size of(struct node));

Read cur->data

cur->link=NULL

37
SINGLY LINKED LIST 8 of 14
Algorithm for creating a node

Step 1: if the list is empty then first==NULL


Step 2: Create a new node
cur= (struct node*) malloc (sizeof (struct node));

Step 3: Read the content of node


Step 4: Assign new node link to NULL
cur->link=NULL
Step 5: Assign new node to first & last node
first=cur
last=cur
Step 6: If the list is not empty call insert function
insert ()
Step 7 : Stop
38
SINGLY LINKED LIST 9 of 14
INSERTION:

How do we place elements in the list: Usually, there are 4 cases we


can use:

•at the beginning

•at the end of the list

•after a given element

•before a given element

39
SINGLY LINKED LIST 10 of 14
Case 1 : at the beginning Pseudo code:
1.Inserting at beginning of list.
2.if (first! = NULL)
3.{
4.Cur=(struct node*) malloc
(sizeof(struct node))
5.Read cur->data
6.Cur->lnk=first
7.First=cur
8.}

40
SINGLY LINKED LIST 11 of 14
Case 2 : end of the list Pseudo code:
1.Inserting at end of list.
2.if (first! = NULL)
3.{
4.Cur=(struct node*) malloc
(sizeof(struct node))
5.Read cur->data
6.Next=first
7.While(next!=NULL)
8.{
Prev=next;
Next=next->link;
}
Cur->link=prev->link;
1. prev->link=cur
2.}

41
SINGLY LINKED LIST 12 of 14
Case 3 : after a given element Pseudo code:
1.Inserting at end of list.
2.if (first! = NULL)
3.{
4.Cur=(struct node*) malloc
(sizeof(struct node))
5.Read cur->data
6.Next=first
7.while(next!=NULL)
8.{
9. if(next->data = = key)
10. break;
11. else
12. next=next->link;
13.}
14.cur -> link = next->link;
15.next->link = cur;
16.}

42
SINGLY LINKED LIST 12 of 14
Case 4 : Before a given element
Pseudo code:
1.Inserting at end of list.
2.if (first! = NULL)
3.{
4.Cur=(struct node*) malloc
(sizeof(struct node))
5.Read cur->data
6.Next=first
7.while(next!=NULL)
8.{
9. if(next->data = = key)
10. break;
11. else
{ prev=next
12. next=next->link; }
13.}
14.cur -> link = prev->link;
15.prev->link = cur;
16.}
43
SINGLY LINKED LIST 12 of 14

DELETION: Removing an element from the list, without destroying the


integrity of the list itself.

When we delete a node we logically remove the node from the list by
changing links and physically remove it from heap

1)deletion from beginning of list


2)deletion at middle of list
3)deletion at end of list

44
SINGLY LINKED LIST 13 of 14
DELETION at the beginning of list:

Pseudo code:

1.While(curr!=NULL)
2. if(curr->data = = key)
3. break;
4. else
5. prev=curr;
6. curr=curr->next;
7.if(curr==header)
8. header = curr->next;
9.else
10. prev->next = curr->next;
11.delete curr;

45
SINGLY LINKED LIST 14 of 14
TRAVERSAL:

Pseudo code:
1.temp = header;
2.while(temp!=NULL)
3. printf(“%d”,temp->data);
4. temp = temp->next;
46
CONCATENATING SINGLY LINKED LISTs

NODE concat(NODE first, NODE


second)
{
NODE cur;
if(first==NULL)
return second;
if(second==NULL)
return first;
cur =first;
while(cur->link!=NULL)
{
cur = cur->link;
}
cur->link = second;
return first;
}

47
CIRCULARLY LINKED LIST
A circularly linked list, or simply circular list, is a linked list in which
the last node is always points to the first node. This type of list can
be build just by replacing the NULL pointer at the end of the list
with a pointer which points to the first node. There is no first or last
node in the circular list.

Advantages:
Any node can be traversed starting from any other node in the list.
There is no need of NULL pointer to signal the end of the list and
hence, all pointers contain valid addresses.
In contrast to singly linked list, deletion operation in circular list is
simplified as the search for the previous node of an element to be
deleted can be started from that item itself.

48
CIRCULARLY LINKED LIST
Insertion at the front of Circular linked list
Procedure for insertion a node at the beginning of list
Step1. Create the new node
Step2. Set the new node‟s next to itself (circular!)
Step3. If the list is empty, return new node.
Step4. Set our new node‟s next to the front.
Step5. Set tail‟s next to our new node.
Step6. Return the end of the list.

49
CIRCULARLY LINKED LIST
Insertion in the middle of the Circular linked list

50
CIRCULARLY LINKED LIST
Insertion at the end of Circular linked list
Procedure for insertion a node at the end of list
Step1. Create the new node
Step2. Set the new node‟s next to itself (circular!)
Step3. If the list is empty,return new node.
Step4. Set our new node‟s next to the front.
Step5. Set tail‟s next to our new node.
Step6. Return the end of the list.

51
CIRCULARLY LINKED LIST
Deletion In Circular linked list
There are three situation for Deleting element in list.
1.Deletion at beginning of the Circular linked list.
2.Deletion at the middle of the Circular linked list.
3.Deletion at the end of the Circular linked list.

52
CIRCULARLY LINKED LIST
1.Deletion at beginning of the Circular linked list.

After Deletion

53
CIRCULARLY LINKED LIST
Deletion at beginning in Circular linked list
Pseudo code:

node=start->next;
ptr=start;
if(i==0)
{
printf("\n List is empty");
exit(0);
}
ptr->next=node->next;
free(node);

54
CIRCULARLY LINKED LIST
Deletion at the middle of the Circular linked list

After Deletion

55
CIRCULARLY LINKED LIST
Deletion at location in Circular linked list
Pseudo code:

if(node_no==delete_no) {
ptr->next=node->next;
free(node);
flag=1;
break;
}
else {
ptr=ptr->next;
node=node->next;
}
node_no++;
count--; }
if(flag==0) {
printf("\n Position not found");

56
CIRCULARLY LINKED LIST
Deletion at the end of the Circular linked list

After Deletion

57
CIRCULARLY LINKED LIST
Deletion at Last Node
Pseudo code:

node=start->next;
ptr=start; count=i;
if(i==0) {
printf("\n List is empty");
exit(0);
}
while(count) {
node_no++;
ptr=ptr->next;
node=node->next;
count--; }
node=start->next;
ptr=start;
while(node_no!=1) {
node_no--;
ptr=ptr->next;
node=node->next;
} if(node_no==1) {
ptr->next=node->next;
free(node); }
58
DOUBLY LINKED LIST
 In a singly linked list one can move from the header node to any
node in one direction only (left-right).

A doubly linked list is a two-way list because one can move in


either direction i.e., either from left to right or from right to left.

It maintains two links or pointers. Hence, it is called as doubly


linked list.
PREV DATA NEXT

Structure of the node


Where, DATA field stores the element or data, PREV contains the
address of its previous node, NEXT contains the address of its next
node.

59
DOUBLY LINKED LIST
struct node
{
int data;
struct node *next; // Pointer to next node in DLL
struct node *prev; // Pointer to previous node in
DLL
};

60
DOUBLY LINKED LIST
Advantages over singly linked list

1) A DLL can be traversed in both forward and backward direction.

2) The delete operation in DLL is more efficient if pointer to the node to


be deleted is given.

In singly linked list, to delete a node, pointer to the previous node is


needed. To get this previous node, sometimes the list is traversed. In
DLL, we can get the previous node using previous pointer.

Disadvantages over singly linked list

1) Every node of DLL Require extra space for an previous pointer. It is


possible to implement DLL with single pointer though.

2) All operations require an extra pointer previous to be maintained. For


example, in insertion, we need to modify previous pointers together
with next pointers. For example in following functions 61
for insertions at
different positions, we need 1 or 2 extra steps to set previous pointer.
DOUBLY LINKED LIST
In this type of liked list each node holds two-pointer field. Pointers exist
between adjacent nodes in both directions. The list can be traversed
either forward or backward

62
DOUBLY LINKED LIST
Creating a New Node
Pseudo code:

ptr=(node*)malloc(sizeof(node));
ptr->info=item;
if(*start==NULL) {
ptr->prev = ptr->next = NULL ;
*start = *end = ptr ;
}
else {
ptr->prev = *end;
(*end)->next = ptr ;
ptr->next= NULL;
(*end)=ptr;
}

63
DOUBLY LINKED LIST
Insertion in doubly linked list
There are three situation for inserting element
in list.
1.Insertion at the front of list.
2.Insertion in the middle of the list.
3.Insertion at the end of the list.
1.Insertion at the front of list

64
DOUBLY LINKED LIST
Insert at front of the list
Algorithm
Pseudo code: InsertAtFrontDll(info,prev,next,st
art,end)
ptr=(node*)malloc(sizeof(node));1.create a new node and address
ptr->info=item; in assigned to ptr.
if(*start==NULL) 2.check[overflow] if(ptr=NULL)
{ write:overflow and exit
*start=ptr; 3.set Info[ptr]=item;
*end=ptr; 4.if(start=NULL)
set prev[ptr] = next[ptr] = NULL
}
set start = end = ptr
else else
{ set prev[ptr] = NULL
ptr->prev = NULL; next[ptr] = start
ptr->next=*start; set prev[start] = ptr
(*start)->prev=ptr; set start = ptr [end if]
*start=ptr; 5.Exit.
}

65
DOUBLY LINKED LIST
2.Insertion in the middle of the list

66
DOUBLY LINKED LIST
2.Insertion in the middle of the list
Pseudo code:
ptr=(node*)malloc(sizeof(node));
ptr->info=item;
loc = *start ;
if(*start==NULL) {
ptr->prev = ptr->next = NULL ;
*start = *end = ptr ; }
else if(i<=size) {
while(n != i) {
loc=loc->next;
n++;
}
ptr->next = loc->next ;
ptr->prev = loc ;
(loc->next)->prev = ptr ;
loc->next = ptr ;
}
else{
ptr->prev = *end;
(*end)->next = ptr ;
ptr->next= NULL;
(*end)=ptr; }}
67
DOUBLY LINKED LIST
3.Insertion at the end of the list

68
DOUBLY LINKED LIST

Insert at the end of Dllist


Pseudo code:
ptr=(node*)malloc(sizeof(node));
ptr->info=item;
if(*start==NULL)
{
ptr->prev = ptr->next = NULL ;
*start = *end = ptr ;
}
else
{
ptr->prev = *end;
(*end)->next = ptr ;
ptr->next= NULL;
(*end)=ptr;
}

69
DOUBLY LINKED LIST
Deletion
In a double linked list, the deletion operation can be performed in three ways as
follows...
• Deleting from Beginning of the list
• Deleting from End of the list
• Deleting a Specific Node
Deleting from Beginning of the list
We can use the following steps to delete a node from beginning of the double
linked list...
Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not
possible' and terminate the function.
Step 3 - If it is not Empty then, define a Node pointer 'temp' and initialize
with head.
Step 4 - Check whether list is having only one node (temp → previous is equal
to temp → next)
Step 5 - If it is TRUE, then set head to NULL and
delete temp (Setting Empty list conditions)
Step 6 - If it is FALSE, then assign temp → next to head, 70 NULL to head →
previous and delete temp.
DOUBLY LINKED LIST
Deleting from End of the list
We can use the following steps to delete a node from end of the double linked
list...
Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty, then display 'List is Empty!!! Deletion is not
possible' and terminate the function.
Step 3 - If it is not Empty then, define a Node pointer 'temp' and initialize
with head.
Step 4 - Check whether list has only one Node (temp → previous and temp →
next both are NULL)
Step 5 - If it is TRUE, then assign NULL to head and delete temp. And
terminate from the function. (Setting Empty list condition)
Step 6 - If it is FALSE, then keep moving temp until it reaches to the last node
in the list. (until temp → next is equal to NULL)
Step 7 - Assign NULL to temp → previous → next and delete temp.

71
DOUBLY LINKED LIST
Deleting a Specific Node from the list
We can use the following steps to delete a specific node from the double linked list...
Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate the
function.
Step 3 - If it is not Empty, then define a Node pointer 'temp' and initialize with head.
Step 4 - Keep moving the temp until it reaches to the exact node to be deleted or to the last node.
Step 5 - If it is reached to the last node, then display 'Given node not found in the list! Deletion
not possible!!!' and terminate the function.
Step 6 - If it is reached to the exact node which we want to delete, then check whether list is having
only one node or not
Step 7 - If list has only one node and that is the node which is to be deleted then
set head to NULL and delete temp (free(temp)).
Step 8 - If list contains multiple nodes, then check whether temp is the first node in the list (temp ==
head).
Step 9 - If temp is the first node, then move the head to the next node (head = head → next),
set head of previous to NULL (head → previous = NULL) and delete temp.
Step 10 - If temp is not the first node, then check whether it is the last node in the list (temp → next
== NULL).
Step 11 - If temp is the last node then set temp of previous of next to NULL (temp → previous →
next = NULL) and delete temp (free(temp)).
Step 12 - If temp is not the first node and not the last node, then
set temp of previous of next to temp of next (temp → previous → next = temp →
next), temp of next of previous to temp of previous (temp → next → previous 72 = temp →
DOUBLY LINKED LIST

Displaying a Double Linked List

We can use the following steps to display the elements of a double linked list...
Step 1 - Check whether list is Empty (head == NULL)
Step 2 - If it is Empty, then display 'List is Empty!!!' and terminate the function.
Step 3 - If it is not Empty, then define a Node pointer 'temp' and initialize
with head.
Step 4 - Display 'NULL <--- '.
Step 5 - Keep displaying temp → data with an arrow (<===>)
until temp reaches to the last node
Step 6 - Finally, display temp → data with arrow pointing to NULL (temp →
data ---> NULL).

73
APPLICATIONS OF LINKED LIST
•Linked Lists can be used to implement Stacks , Queues. Linked Lists can also be
used to implement Graphs. (Adjacency list representation of Graph).
•Implementing Hash Tables :- Each Bucket of the hash table can itself be a
linked list. (Open chain hashing).
•Undo functionality in Photoshop or Word . Linked list of states.
•A polynomial can be represented in an array or in a linked list by simply
storing the coefficient and exponent of each term.
•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
74
the linked list until all the applications are completed.
Representation of single, two dimensional arrays(1 of 6)

Arrays

Array: a set of pairs, <index, value>

data structure
For each index, there is a value associated with that
index.

representation (possible)

Implemented by using consecutive memory.


In mathematical terms, we call this a
correspondence or a mapping.
75
Representation of single, two dimensional arrays(2 of 6)

When considering an ADT we are more concerned


with the operations that can be performed on an
array. Aside from creating a new array, most languages
provide only two standard operations for arrays, one that
retrieves a value, and a second that stores a value.

The advantage of this ADT definition is that it clearly points


out the fact that the array is a more general structure than
“a consecutive set of memory locations.”

76
Representation of single, two dimensional arrays 3 of 6
Memory Contents of
Address Memory Location

2A 3014 00

Integer (0) Integer (1) Integer (2) Integer (3) Integer (4) Integer (5)
2A 3015 00
2A 3016 04
2A 3017 B9
/* Declare array */ 2A 3018 00
int aiEmployeeNumbers [6]; 2A 3019 00
2A 301A 00
2A 301B 08
2A 301C 00
2A 301D 00
125 2A 301E 00
1023
-255 2A 301F 0F
15
8 2A3020 80
1209 5 2A 3021 00
4

2A 3022 00
3
2

2A 3023 7C
1

2A 3024 00
0

ay
Arr ex Uninitialized Integer Array 2A 3025 00
Ind (Conceptual) 2A 3026 03
2A 3027 FF
2A3028 00
2A 3029 00
How an integer array 2A 302A 77 00
looks in memory? 2A 302B 7D
Representation of single, two dimensional arrays 4 of 6

Arrays in C
int list[5], *plist[5];
list[5]: (five integers) list[0], list[1], list[2], list[3], list[4]
*plist[5]: (five pointers to integers)
plist[0], plist[1], plist[2], plist[3], plist[4]
implementation of 1-D array
list[0] base address = 
list[1]  + sizeof(int)
list[2]  + 2*sizeof(int)
list[3]  + 3*sizeof(int)
list[4]  + 4*sizeof(int)

78
Representation of single, two dimensional arrays 5 of 6
2-dimensional arrays provide most of this
capability. Like a 1D array, a 2D array is a
collection of data cells, all of the same type, which
can be given a single name. However, a 2D array is
organized as a matrix with a number of rows and
columns.
imilar to the 1D array, we must specify the data
type, the name, and the size of the array. But the
size of the array is described as the number of
rows and number of columns.

For example: int a[MAX_ROWS][MAX_COLS];


79
Representation of single, two dimensional arrays 6 of 6
This declares a data structure that looks like:

80
Sparse Matrices

In computer programming, a matrix can be defined with a


2-dimensional array. Any array with 'm' columns and 'n'
rows represent a m X n 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 Representations


A sparse matrix can be represented by using TWO
representations, those are as follows...
1. Triplet Representation (Array Representation)
2. Linked Representation

81
Sparse Matrices
Triplet Representation (Array Representation)

In this representation, we consider only non-zero


values along with their row and column index
values. In this representation, the 0throw stores
the total number of rows, total number of columns
and the total number of non-zero values in the
sparse matrix.

For example, consider a matrix of size 5 X 6


containing 6 number of non-zero values. This
matrix can be represented as shown in the image...
82
Sparse Matrices

In above example matrix, there are only 6 non-zero elements ( those are
9, 8, 4, 2, 5 & 2) and matrix size is 5 X 6. We represent this matrix as
shown in the above image. Here the first row in the right side table is
filled with values 5, 6 & 6 which indicates that it is a sparse matrix with
5 rows, 6 columns & 6 non-zero values. The second row is filled with 0,
4, & 9 which indicates the non-zero value 9 is at the 0th-row 4th column
in the Sparse matrix. In the same way, the remaining non-zero values
also follow a similar pattern. 83
Sparse Matrices
Linked Representation
In linked representation, we use a linked list data structure to represent a
sparse matrix. In this linked list, we use two different nodes namely header
node and element node. Header node consists of three fields and element node
consists of five fields as shown in the image...

84
Sparse Matrices
Consider the above same sparse matrix used in the Triplet representation. This
sparse matrix can be represented using linked representation as shown in the
below image...

In the above representation, H0, H1,..., H5 indicates the header nodes which are used to
represent indexes. Remaining nodes are used to represent non-zero elements in the
matrix, except the very first node which is used to represent abstract information of the
sparse matrix (i.e., It is a matrix of 5 X 6 with 6 non-zero elements).

In this representation, in each row and column, the last node right field points to its
85
respective header node.

Das könnte Ihnen auch gefallen