0% found this document useful (0 votes)
8 views

ds-unit-3

Uploaded by

Santhosh Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

ds-unit-3

Uploaded by

Santhosh Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

UNIT -III

Linked List:
A linked list is a sequence of data structures, which are connected together via
links.
Linked List is a sequence of links which contains items. Each link contains a
connection to another link. Linked list is the second most-used data structure after
array. Following are the important terms to understand the concept of Linked List.
 Link − Each link of a linked list can store a data called an element.
 Next − Each link of a linked list contains a link to the next link called Next.
 LinkedList − A Linked List contains the connection link to the first link
called First.

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 list:


 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 travelling is difficult in linked list.

Applications of Linked List:


 Linked lists are used to implement stacks, queues, graphs, etc.
 Linked lists let you insert elements at the beginning and end of the list.
 In linked lists we don’t need to know the size in advance.

Linked List Representation


Linked list can be visualized as a chain of nodes, where every node points to the
next node.

As per the above illustration, following are the important points to be considered.
 Linked List contains a link element called first.
 Each link carries a data field(s) and a link field called next.
 Each link is linked with its next link using its next link.
 Last link carries a link as null to mark the end of the list.

Types of Linked List


Following are the various types of linked list.
 Simple Linked List − Item navigation is forward only.
 Doubly Linked List − Items can be navigated forward and backward.
 Circular Linked List − Last item contains link of the first element as next
and the first element has a link to the last element as previous.

Basic Operations
Following are the basic operations supported by a list.
 Insertion − Adds an element at the beginning of the list.
 Deletion − Deletes an element at the beginning of the list.
 Display − Displays the complete list.
 Search − Searches an element using the given key.
 Delete − Deletes an element using the given key.

Insertion Operation
Adding a new node in linked list is a more than one step activity. We shall learn
this with diagrams here. First, create a node using the same structure and find the
location where it has to be inserted.

Imagine that we are inserting a node B (NewNode), between A (LeftNode)


and C (RightNode). Then point B.next to C −
NewNode.next −> RightNode;
It should look like this −
Now, the next node at the left should point to the new node.
LeftNode.next −> NewNode;

This will put the new node in the middle of the two. The new list should look like
this −

Similar steps should be taken if the node is being inserted at the beginning of the
list. While inserting it at the end, the second last node of the list should point to the
new node and the new node will point to NULL.

Deletion Operation
Deletion is also a more than one step process. We shall learn with pictorial
representation. First, locate the target node to be removed, by using searching
algorithms.
The left (previous) node of the target node now should point to the next node of the
target node −
LeftNode.next −> TargetNode.next;

This will remove the link that was pointing to the target node. Now, using the
following code, we will remove what the target node is pointing at.
TargetNode.next −> NULL;

We need to use the deleted node. We can keep that in memory otherwise we can
simply deallocate memory and wipe off the target node completely.

Reverse Operation
This operation is a thorough one. We need to make the last node to be pointed by
the head node and reverse the whole linked list.

First, we traverse to the end of the list. It should be pointing to NULL. Now, we
shall make it point to its previous node −
We have to make sure that the last node is not the last node. So we'll have some
temp node, which looks like the head node pointing to the last node. Now, we shall
make all left side nodes point to their previous nodes one by one.

Except the node (first node) pointed by the head node, all nodes should point to
their predecessor, making them their new successor. The first node will point to
NULL.

We'll make the head node point to the new first node by using the temp node.

The linked list is now reversed. To see linked list implementation in C


programming language,

Doubly Linked List


Doubly Linked List is a variation of Linked list in which navigation is possible in
both ways, either forward and backward easily as compared to Single Linked List.
Following are the important terms to understand the concept of doubly linked list.
 Link − Each link of a linked list can store a data called an element.
 Next − Each link of a linked list contains a link to the next link called Next.
 Prev − Each link of a linked list contains a link to the previous link called
Prev.
 LinkedList − A Linked List contains the connection link to the first link
called First and to the last link called Last.
Doubly Linked List Representation

As per the above illustration, following are the important points to be considered.
 Doubly Linked List contains a link element called first and last.
 Each link carries a data field(s) and two link fields called next and prev.
 Each link is linked with its next link using its next link.
 Each link is linked with its previous link using its previous link.
 The last link carries a link as null to mark the end of the list.

Basic Operations
Following are the basic operations supported by a list.
 Insertion − Adds an element at the beginning of the list.
 Deletion − Deletes an element at the beginning of the list.
 Insert Last − Adds an element at the end of the list.
 Delete Last − Deletes an element from the end of the list.
 Insert After − Adds an element after an item of the list.
 Delete − Deletes an element from the list using the key.
 Display forward − Displays the complete list in a forward manner.
 Display backward − Displays the complete list in a backward manner.

Insertion Operation
Following code demonstrates the insertion operation at the beginning of a doubly
linked list.
Example
//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;
} 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;
}

Deletion Operation
Following code demonstrates the deletion operation at the beginning of a doubly
linked list.
Example
//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;
}

Insertion at the End of an Operation


Following code demonstrates the insertion operation at the last position of a doubly
linked list.
Example
//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;
}

Circular Linked List


Circular Linked List is a variation of Linked list in which the first element points to
the last element and the last element points to the first element. Both Singly Linked
List and Doubly Linked List can be made into a circular linked list.

Singly Linked List as Circular


In singly linked list, the next pointer of the last node points to the first node.

Doubly Linked List as Circular


In doubly linked list, the next pointer of the last node points to the first node and
the previous pointer of the first node points to the last node making the circular in
both directions.
As per the above illustration, following are the important points to be considered.
 The last link's next points to the first link of the list in both cases of singly as well as
doubly linked list.
 The first link's previous points to the last of the list in case of doubly linked list.

Basic Operations

Following are the important operations supported by a circular list.


 insert − Inserts an element at the start of the list.
 delete − Deletes an element from the start of the list.
 display − Displays the list.

Insertion Operation

Following code demonstrates the insertion operation in a circular linked list based on single
linked list.
Example
insertFirst(data):
Begin
create a new node
node -> data := data
if the list is empty, then
head := node
next of node = head
else
temp := head
while next of temp is not head, do
temp := next of temp
done
next of node := head
next of temp := node
head := node
end if
End

Deletion Operation
Following code demonstrates the deletion operation in a circular linked list based on single
linked list.
deleteFirst():
Begin
if head is null, then
it is Underflow and return
else if next of head = head, then
head := null
deallocate head
else
ptr := head
while next of ptr is not head, do
ptr := next of ptr
next of ptr = next of head
deallocate head
head := next of ptr
end if
End

Display List Operation

Following code demonstrates the display list operation in a circular linked list.
display():
Begin
if head is null, then
Nothing to print and return
else
ptr := head
while next of ptr is not head, do
display data of ptr
ptr := next of ptr
display data of ptr
end if
End
Applications of Linked lists:
Application of linked list in computer science—

1. Implementation of stacks and queues


2. Implementation of graphs: Adjacency list representation of graphs is most popular
which uses linked list to store adjacent vertices.
3. Dynamic memory allocations : we use linked list of free blocks.
4. Maintaining directory of names.
5. Performing arithmetic operations on long integers.
6. Manipulation of polynomials by using storing constants in the node of linked list
representing sparse matrices.
Applications of linked list in real world-
l. Image viewer - Previous and next images are linked, hence can be accessed by next and
previous button.
2. Previous and next page in web browser - We can access previous and next url searched
in web browser by pressing back and next button since, they are linked as linked list.
3. Music Player - Songs in music player are linked to previous and next song. you can
play songs either from starting or ending of the list.

Applications of Circular Linked Lists:


1. Useful for implementation of queue. Unlikethisimplementation, we don't need to
maintain two pointers for front and rear if we use circular linked list. We can maintain a
pointer to the last inserted node and front can always be obtained as next of last.
2. Circular lists are useful in applications to repeatedly go around the list. For example,
when multiple applications are running on a PC, it is common for the operating system
to put the running applications on a list and then to cycle through them, giving each of
them a slice of time to execute, and then making them wait while the CPU is given to
another application. It is convenient for the operating system to use a circular list so that
when it reaches the end of the list it can cycle around to the front of the list.
3. Circular Doubly Linked Lists are used for implementation of advanced data structures
like Fibonacci Heap.

Basic Operations on Linked List


' Traversal: To travefse all the nodes one after another.
. Insertion: To add a node at the given position.
. Deletion: To delete a node.
" Searching: To search an element(s) by value.
. Updating: To update a node.
. Sorting: To arrange nodes in a linked list in a specific order.
. Merging: To merge two linked lists into one.

1. Linked List Traversal


The idea here is to step through the list from beginning to end. For example, we may want
to print the list or search for a specific node in the list.
The algorithm for traversing a list
. Start with the head of the list. Access the content of the head node if it is not null.
. Then go to the next node(if exists) and access the node information
. Continue until no more nodes (that is" vou have reached the null node)
2. Linked List node Insertion
There can be three cases that vvill occur when we are insertins a node in a linked list.
. Inseftion at the beginning
. lnserlion at the end. (Append)
' Insertion aft"er a siven node
Insertion at the beginning
r Since there is no need to find the end of the list.
. If the list is en-rpty, we rnake the new node as the head of the list.
. Otherwise, we have to connect the new node to the current head of the list and make
the new node, the head of the list.

n+wl4cd*
Insertlon ct the beginnlng
Insertion at end
. We will traverse the lisr until we find the last node.
. Then we insert the new node to the end of the list.
r Note that we have to consider special cases such as list being empty.
I In case of a list being empty, we will return the updated head of the linked list
because in this case, the inserted node is the first as well as the last node of the
linked list.

now
Insertlon at the cnd
Insertion nfter t given node
We are given the reference to a node, and the new node is inserted after the given node.
i
nswNoda
Insertlon after a given node

3. Linked List node Deletion


To delete a node fi'om a linked list, we need to do these steps
. Find the previous node of the node to be deleted.
. Change the nep pointer ofthe previous node
' Free the memory of the deleted node.
In the deletion, there is a special case in which the first node is deleted.
In this, we need to update the head of the linked list.

{
r
Ileleting a ilde in Llnked List

4. Linked List node Searching


Io search any value in the linked list, we can traverse the linked list and compares the value
present in the node.

5. Linked List node Updation


To update the value of the node, we just need to set the data pari to the new value.

*******
Polynomials using linked list and Arrays.
Polynomials and Sparse Matrix are two important applications of arrays and linked lists. A
polynomial is composed of different terms where each of them holds a coefficient and an
exponent. This tutorial chapter includes the representation of polynomials using linked lists and
arrays.

What is polynomial?

A polynomial p(x) is the expression in variable x which is in the form (ax n + bxn-1 + …. + jx+ k),
where a, b, c …., k fall in the category of real numbers and 'n' is non negative integer, which is
called the degree of polynomial.

An essential characteristic of the polynomial is that each term in the polynomial expression
consists of two parts:

 one is the coefficient


 other is the exponent

Representation of Polynomial

Polynomial can be represented in the various ways. These are:

 By the use of arrays


 By the use of Linked List

Representation of Polynomials Using Arrays

There may arise some situation where you need to evaluate many polynomial expressions and
perform basic arithmetic operations like addition and subtraction with those numbers. For this,
you will have to get a way to represent those polynomials. The simple way is to represent a
polynomial with degree 'n' and store the coefficient of n+1 terms of the polynomial in the array.
So every array element will consist of two values:

 Coefficient and
 Exponent

A polynomial can be represented using the C++ code:

#include <iostream>
#include <iomanip.h>
using namespace std;

struct poly {
int coeff;
int pow_val;
poly* next;
};

class add {
poly *poly1, *poly2, *poly3;

public:
add() { poly1 = poly2 = poly3 = NULL; }
void addpoly();
void display();
};

void add::addpoly()
{
int i, p;
poly *newl = NULL, *end = NULL;
cout << "Enter highest power for x\n"; cin >> p;
//Read first poly
cout << "\nFirst Polynomial\n"; for (i = p; i >= 0; i--) {
newl = new poly;
newl->pow_val = p;
cout << "Enter Co-efficient for degree" << i << ":: "; cin >> newl->coeff;
newl->next = NULL;
if (poly1 == NULL)
poly1 = newl;
else
end->next = newl;
end = newl;
}

//Read Second poly


cout << "\n\nSecond Polynomial\n"; end = NULL; for (i = p; i >= 0; i--) {
newl = new poly;
newl->pow_val = p;
cout << "Enter Co-efficient for degree" << i << ":: "; cin >> newl->coeff;
newl->next = NULL;
if (poly2 == NULL)
poly2 = newl;
else
end->next = newl;
end = newl;
}

//Addition Logic
poly *p1 = poly1, *p2 = poly2;
end = NULL;
while (p1 != NULL && p2 != NULL) {
if (p1->pow_val == p2->pow_val) {
newl = new poly;
newl->pow_val = p--;
newl->coeff = p1->coeff + p2->coeff;
newl->next = NULL;
if (poly3 == NULL)
poly3 = newl;
else
end->next = newl;
end = newl;
}
p1 = p1->next;
p2 = p2->next;
}
}

void add::display()
{
poly* t = poly3;
cout << "\n\nAnswer after addition is : ";
while (t != NULL) {
cout.setf(ios::showpos);
cout << t->coeff;
cout.unsetf(ios::showpos);
cout << "X" << t->pow_val;
t = t->next;
}
}
int main()
{
add obj;
obj.addpoly();
obj.display();
}

Output:
Representation of polynomial using linked list:
A polynomial can be thought of as an ordered list of non zero terms. Each non zero term is a
two-tuple which holds two pieces of information:

 The exponent part


 The coefficient part

Program for addition of polynomials


#include <iostream>
using namespace std;

class polyll {
private:
struct polynode {
float coeff;
int exp;
polynode* link;
} * p;

public:
polyll();
void poly_append(float c, int e);
void display_poly();
void poly_add(polyll& l1, polyll& l2);
~polyll();
};
polyll::polyll()
{
p = NULL;
}
void polyll::poly_append(float c, int e)
{
polynode* temp = p;
if (temp == NULL) {
temp = new polynode;
p = temp;
}
else {
while (temp->link != NULL)
temp = temp->link;
temp->link = new polynode;
temp = temp->link;
}
temp->coeff = c;
temp->exp = e;
temp->link = NULL;
}
void polyll::display_poly()
{
polynode* temp = p;
int f = 0;

cout << endl; while (temp != NULL) { if (f != 0) { if (temp->coeff > 0)


cout << " + ";
else
cout << " "; } if (temp->exp != 0)
cout << temp->coeff << "x^" << temp->exp;
else
cout << temp->coeff;
temp = temp->link;
f = 1;
}
}
void polyll::poly_add(polyll& l1, polyll& l2)
{
polynode* z;
if (l1.p == NULL && l2.p == NULL)
return;
polynode *temp1, *temp2;
temp1 = l1.p;
temp2 = l2.p;
while (temp1 != NULL && temp2 != NULL) {
if (p == NULL) {
p = new polynode;
z = p;
}
else {
z->link = new polynode;
z = z->link;
}
if (temp1->exp < temp2->exp) {
z->coeff = temp2->coeff;
z->exp = temp2->exp;
temp2 = temp2->link;
}
else {
if (temp1->exp > temp2->exp) {
z->coeff = temp1->coeff;
z->exp = temp1->exp;
temp1 = temp1->link;
}
else {
if (temp1->exp == temp2->exp) {
z->coeff = temp1->coeff + temp2->coeff;
z->exp = temp1->exp;
temp1 = temp1->link;
temp2 = temp2->link;
}
}
}
}
while (temp1 != NULL) {
if (p == NULL) {
p = new polynode;
z = p;
}
else {
z->link = new polynode;
z = z->link;
}
z->coeff = temp1->coeff;
z->exp = temp1->exp;
temp1 = temp1->link;
}
while (temp2 != NULL) {
if (p == NULL) {
p = new polynode;
z = p;
}
else {
z->link = new polynode;
z = z->link;
}
z->coeff = temp2->coeff;
z->exp = temp2->exp;
temp2 = temp2->link;
}
z->link = NULL;
}
polyll::~polyll()
{
polynode* q;
while (p != NULL) {
q = p->link;
delete p;
p = q;
}
}
int main()
{
polyll p1;
p1.poly_append(1.4, 5);
p1.poly_append(1.5, 4);
p1.poly_append(1.7, 2);
p1.poly_append(1.8, 1);
p1.poly_append(1.9, 0);
cout << "\nFirst polynomial:";
p1.display_poly();
polyll p2;
p2.poly_append(1.5, 6);
p2.poly_append(2.5, 5);
p2.poly_append(-3.5, 4);
p2.poly_append(4.5, 3);
p2.poly_append(6.5, 1);
cout << "\nSecond polynomial:";
p2.display_poly();
polyll p3;
p3.poly_add(p1, p2);
cout << "\nResultant polynomial: ";
p3.display_poly();
getch();
}
Output:
Sparse Matrix
What is Sparse Matrix?

In computer programming, a matrix can be defined with a 22-dimensional


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
NON-ZERO RO values. Such matrix is known as sparse
matrix.

Sparse matrix is a matrix which contains very few non


non-zero
zero elements.
elements

When a sparse matrix is represented with a 22-dimensional


dimensional array, we waste a lot of space to
represent that matrix. For example, consider a matrix of size 100 X 100 containing only 10 non-
non
zero elements. In this matrix, only 10 spaces are filled with non non-zero values and remaining
spaces of the 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
non-zero
zero elements we have to
make scanning for 10000 times. To make iitt simple we use the following sparse matrix
representation.

Sparse Matrix Representations

A sparse matrix can be represented by using TWO representations, those are as follows...

 Triplet Representation (Array Representation)


 Linked Representation

Triplet Representation
epresentation (Array Representation)

In this representation, we consider only nonnon-zero


zero values along with their row and column
th
index values. In this representation, the 0 row stores the total number of rows, total number
of columns and the total number of non-zero zero values in the sparse matrix.
For example, consider a matrix of size 5 X 6 containing 6 number of non non-zero
zero values. This
matrix can be represented as shown in the image...
In above example matrix, there are only 6 non
non-zero
zero elements ( those are 9, 8, 4, 2, 5 & 2) and
matrix size is 5 X 6. We represent this matrix as shoshown
wn 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 non-zero
zero values. The second row is filled with 0, 4, & 9
which indicates the non-zero
zero val
value 9 is at the 0th-row
row 4th column in the Sparse matrix. In the
same way, the remaining non
non-zero values also follow a similar pattern.

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. node Header
node consists of three fields and element node consists of five fields as shown in the image...

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 non-zero
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
non-zero elements).

You might also like