Linked Listnotes

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

LINKED LIST

A linked list is the most sought-after data structure when it comes to handling dynamic data
elements. A linked list consists of a data element known as a node. And each node consists of
two fields: one field has data, and in the second field, the node has an address that keeps a
reference to the next node.

What is a Linked List?

• A linked list is a linear data structure that stores a collection of data elements
dynamically.

• Nodes represent those data elements, and links or pointers connect each node.

• Each node consists of two fields, the information stored in a linked list and a pointer
that stores the address of its next node.

• The last node contains null in its second field because it will point to no node.

• A linked list can grow and shrink its size, as per the requirement.

• It does not waste memory space.

Representation of a Linked List

This representation of a linked list depicts that each node consists of two fields. The first field
consists of data, and the second field consists of pointers that point to another node.
Here, the start pointer stores the address of the first node, and at the end, there is a null pointer
that states the end of the Linked List.

Creation of Node and Declaration of Linked Lists

struct node

int data;

struct node * next;


};

It is a declaration of a node that consists of the first variable as data and the next as a pointer,
which will keep the address of the next node.

Here you need to use the malloc function to allocate memory for the nodes dynamically.

Discuss advantages and disadvantages of linked list over array.

Advantages of an array
1. We can access any element of an array directly means random access is easy
2. It can be used to create other useful data structures (queues, stacks)
3. It is light on memory usage compared to other structures

Disadvantages of an array
1. Its size is fixed
2. It cannot be dynamically resized in most languages
3. It is hard to add/remove elements
4. Size of all elements must be same.
5. Rigid structure (Rigid = Inflexible or not changeable)

Advantages of Linked List


1. Dynamic size
2. It is easy to add/remove/change elements
3. Elements of linked list are flexible, it can be primary data type or user defined data types

Disadvantages of Linked List


1. Random access is not allowed. We have to access elements sequentially starting from the
first node. So we cannot do binary search with linked lists.
2. It cannot be easily sorted
3. We must traverse 1/2 the list on average to access any element
4. More complex to create than an array
5. Extra memory space for a pointer is required with each element of the list

Types of Linked Lists

The linked list mainly has three types, they are:

1. Singly Linked List

2. Doubly Linked List

3. Circular Linked List

I. Singly Linked List

A singly linked list is the most common type of linked list. Each node has data and an address
field that contains a reference to the next node.

II. Doubly Linked List

There are two pointer storage blocks in the doubly linked list. The first pointer block in each
node stores the address of the previous node. Hence, in the doubly linked inventory, there are
three fields that are the previous pointers, that contain a reference to the previous node. Then
there is the data, and last you have the next pointer, which points to the next node. Thus, you can
go in both directions (backward and forward).
III. Circular Linked List

The circular linked list is extremely similar to the singly linked list. The only difference is that
the last node is connected with the first node, forming a circular loop in the circular linked list.

Circular link lists can either be singly or doubly-linked lists.

• The next node's next pointer will point to the first node to form a singly linked list.

• The previous pointer of the first node keeps the address of the last node to form a
doubly-linked list.

Essential Operation on Linked Lists

• Traversing: To traverse all nodes one by one.


• Insertion: To insert new nodes at specific positions.

• Deletion: To delete nodes from specific positions.

• Searching: To search for an element from the linked list.

➢ Singly linked list


Traversal

In this operation, you will display all the nodes in the linked list.

When the temp is null, it means you traversed all the nodes, and you reach the end of the linked
list and get out from the while loop.

struct node * temp = start;

printf(“\n list empty are-”);

while (temp!= NULL)

printf(‘%d “, temp -> data)

temp=temp -> next;

}
Insertion

You can add a node at the beginning, middle, and end.

1. Insert node at the beginning


• Create a memory for a new node.

• Store data in a new node.

• Change next to the new node to point to start.

• Change starts to tell the recently created node.

struct node *NewNode;

NewNode=malloc(sizeof(struct node));

NewNode -> data = 40;

NewNode -> next= start;

start= NewNode;

2. Insert node at last


• Insert a new node and store data in it.

• Traverse the last node of a linked list

• Change the next pointer of the last node to the newly created node.

struct node *NewNode;

NewNode=malloc(sizeof(struct node));

NewNode-> data = 40;

NewNode->next = NULL;

struct node *temp = start;

while( temp->next ! = NULL){

temp=temp -> next;

temp -> next = NewNode;


3. Insert node at position
• Allocate memory and store data in the new node.

• Traverse the node, which is just before the new node.

• Change the next pointer to add a new node in between.

struct node *NewNode;

NewNode= malloc(sizeof(struct node));

NewNode -> data = 40;

struct node - > temp = start;

While(i<pos){

if (temp -> next!= NULL)

temp = temp -> next;

i++
}}

NewNode -> next = temp -> next;

temp -> next = NewNode;


Deletion
You can also do deletion in the linked list in three ways either from the end, beginning, or from a
specific position.

1. Delete the first Node


• The point starts at the second node.

start = start -> next;

2. Delete the node at End


• Traverse the second last element in the linked list.

• Change its next pointer to null.


struct node * temp = start;

while(temp -> next -> next!= NULL){

temp=temp -> next;

temp -> next = NULL;

3. Delete node at position


• Traverse the element before the element to be deleted.

• Change the next pointer to exclude the node from the linked list.
While(i<pos-1){

if (temp -> next ! = NULL)

temp = temp -> next;

i++

temp-> next = temp -> next -> next;


➢ Doubly linked list
A doubly linked list is a complex version of a singly linked list where each node
contains a pointer to its previous node as well as the next node. Each node in the
doubly linked list has three parts, the first part points to the previous node, the middle
part contains the data and the last part points to the next node.

Operations on doubly linked list


• Insert: adding a new node to the existing doubly linked list.
• Delete: removing a node from the existing doubly linked list.
• Search: finding a node containing the search data in the existing doubly
linked list.
• Display: display the existing doubly linked list.

Creating node in Doubly Linked List


C program to create a node in a doubly-linked list:
struct node

struct node *prev; //NULL for first node

int data; // data to store in node

struct node *next; //NULL for last node

};

Traversing a doubly linked list


Visit each node from start to end one by one.

void printList(struct Node* n)

while (n != NULL) {

printf(" %d ", n->data);

n = n->next;

Insertion in Doubly Linked List


1. Insertion at the beginning in Doubly Linked List
Point the next pointer of the new node to the first node and point the previous pointer
of the current first node to the new node. Point previous of new node to NULL. The
new node is now the first node of the linked list.

void insertAtBegin(node *newnode)

newnode->next = head;

head -> previous = newnode;


head = newnode;

2. Insertion at the end in Doubly Linked List


To add the node in the last position, point the next pointer of the last node to the new
node and point the previous pointer of the new node to the current last node. Point the
next of the new node to null.

Void AddAtEnd(node *newnode)

while (temp -> next != NULL)

temp= temp-> next;

temp-> next = newnode;

newnode -> previous = temp;

newnode-> next = NULL;

OR

tail-> next = newnode;

newnode -> previous = tail;

new -> next = NULL;

tail=newnode
}

3. Adding node at a specific position in Doubly Linked List


If you want to add a node at the nth position, point the next pointer of the new node to the
(n+1)th node and point the previous pointer of the new node to (n-1)th node. After that, point the
next of (n-1)th node and previous of (n+1)th node to the new node.

Void AddAtPosition(node *newnode, node *temp)

temp=head;

While(i<pos-1)

temp=temp -> next

i++

newnode -> prev = temp;

newnode -> next = temp-> next;

temp-> next= newnode;

(newnode -> next) -> prev = newnode;}


Deleting node in Doubly Linked List
1. Delete node at the beginning of Doubly Linked List
Point the next pointer of the first node and the previous pointer of the second node to
null.

void DeleteAtFirst()

Node *temp = *head;

head = head -> next;

head -> prev = NULL;

free(temp);

2. Delete node at the end of Doubly Linked List


Point next pointer of the second last node and previous pointer of the last node to null.

void DeleteAtLast()

{ node *temp;

If(tail==0)
Linklist is empty

temp = tail;

tail -> prev->next =NULL;

tail=tail->next

free temp;

3. Delete node at any position in Doubly Linked List


If you want to delete the node at the nth position, point the next of (n-1)th to (n+1)th node and
point the previous of (n+1)th node to the(n-1)th node. Point previous and next of nth node to
null.

void DeleteAtPosition(int pos)


{
struct node *temp
temp=head;
while(i<pos)
{
temp = temp->next;
i++;
}
temp -> prev -> next= temp->next
temp -> next -> prev = temp->prev
free(temp);
}
➢ Circular Linked List
A circular linked list is a more efficient version of a singly linked list where the last node points
to the first node instead of NULL. Just like a singly linked list, here also each node has two parts.

The first part contains data and the second part points to the next node. It contains the address of
the next node in the actual memory.

Operations on Circular Linked List


• Insert: inserting a new node into a circular linked list.
• Delete: deleting a node from a circular linked list.
• Search: finding a node in a circular linked list.
• Display: displaying the circular linked list.

Insert Node in Circular Linked List


1. Insert Node at the beginning of Circular Linked List
For Adding node at the beginning of the list, Unlink the last and first node and point
the last node to the new node. Now point the new node to the head node and make the
new node the new head.

void insertAtFirst(node *newnode)

If(Last==0)
{

Last=newnode

Last->next=newnode;

Else{

newnode->next = Last->next;

Last -> next =newnode;

2. Insert node at the end of Circular Linked List


For adding a node at the end of the list, unlink the last and first node and point the last node to
the new node. Now point new node to head node.

void insertAtLAst(Node *newnode)

If(Last==0)

Last=newnode;

Last->next=newnode;

Else

newnode->next=Last->next;

Last->next=newnode;
Last=newnode;

3. Insert node at any position in Circular Linked List


• For insertion at the given position, we will traverse the circular linked list, and points the
next of the new node to the next node.

void insertAtPos(Node *new)

if(pos<0||pos<length)

invalid position

elseif (pos==1)

Insert atbeg()

Else

{temp=Last->next;

While(i<pos-1)

temp=temp->next;

i++;

}
newnode->next=temp->next;

temp->next=newnode;

Delete Nodes in Circular Linked List


1. Deleting node at the start of Circular Linked List
Delete an existing node from the first position in the list. Point the head to the second
node.

void deleteAtFirst()

temp=Last->next

if(Last==NULL)

list is empty

elseif(temp->next==temp)

{Last=0;

Free(temp)

Else

{Last->next=temp->next;

Free(temp)

2. Delete node at the last of Circular Linked List


Delete an existing node from the last position of the list. Unlink last node to head and point
second last node to head node.
void deleteAtLast()

{ node *temp1,temp2;

temp=Last->next

if(Last==NULL)

list is empty

elseif(temp->next==temp)

{Last=0;

Free(temp)

Else

{ While(temp1->next!=Last->next)

temp2=temp1;

temp1=temp1->next;

temp2->next=Last->next;

Last=temp2;

Free(temp1);

3. Delete node at any Position in Circular Linked List


• to delete the node from a given position, you need to traverse the list and store
the address of the previous node, and point the next of the current node to the
next node.
void deleteAtpos()

if(pos<0||pos<length)

invalid position

elseif (pos==1)

Insert atbeg()

Else{

While(i<pos-1)

temp1=temp1->next;

i++;

Temp2=temp1->next;

temp1->next=temp2->next;

free(temp2);

Applications of linked list in computer science:


1. Implementation of stacks and queues
2. Implementation of graphs: Adjacency list representation of graphs is the most
popular which uses a linked list to store adjacent vertices.
3. Dynamic memory allocation: We use a linked list of free blocks.
4. Maintaining a directory of names
5. Performing arithmetic operations on long integers
6. Manipulation of polynomials by storing constants in the node of the linked
list
7. Representing sparse matrices
Applications of linked list in the real world:
1. Image viewer – Previous and next images are linked and can be accessed by
the next and previous buttons.
2. Previous and next page in a web browser – We can access the previous and
next URL searched in a web browser by pressing the back and next buttons
since they are linked as a linked list.
3. Music Player – Songs in the music player are linked to the previous and next
songs. So you can play songs either from starting or ending of the list.
4. GPS navigation systems- Linked lists can be used to store and manage a list
of locations and routes, allowing users to easily navigate to their desired
destination.
5. Robotics- Linked lists can be used to implement control systems for robots,
allowing them to navigate and interact with their environment.
6. Task Scheduling- Operating systems use linked lists to manage task
scheduling, where each process waiting to be executed is represented as a
node in the list.
7. Image Processing- Linked lists can be used to represent images, where each
pixel is represented as a node in the list.
8. File Systems- File systems use linked lists to represent the hierarchical
structure of directories, where each directory or file is represented as a node
in the list.
9. Symbol Table- Compilers use linked lists to build a symbol table, which is a
data structure that stores information about identifiers used in a program.
10. Undo/Redo Functionality- Many software applications implement undo/redo
functionality using linked lists, where each action that can be undone is
represented as a node in a doubly linked list.
11. Speech Recognition- Speech recognition software uses linked lists to
represent the possible phonetic pronunciations of a word, where each possible
pronunciation is represented as a node in the list.
12. Polynomial Representation- Polynomials can be represented using linked
lists, where each term in the polynomial is represented as a node in the list.
13. Simulation of Physical Systems- Linked lists can be used to simulate physical
systems, where each element in the list represents a discrete point in time and
the state of the system at that time.
Applications of Circular Linked Lists:
1. Useful for implementation of a queue. Unlike this implementation, we don’t
need to maintain two-pointers for the front and rear if we use a circular linked
list. We can maintain a pointer to the last inserted node and the front can
always be obtained as next of last.
2. Circular lists are useful in applications to go around the list repeatedly. 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 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 the implementation of advanced
data structures like the Fibonacci Heap.
4. Circular linked lists can be used to implement circular queues, which are
often used in operating systems for scheduling processes and managing
memory allocation.
5. Used in database systems to implement linked data structures, such as B+
trees, which are used to optimize the storage and retrieval of data.
6. Circular linked lists can be used in networking. For instance, to implement
circular buffers for streaming data, such as video and audio, in networking
applications.
7. Video games use circular linked lists to manage sprite animations. Each
frame of the animation is represented as a node in the list, and the last frame
is connected to the first frame to create a loop.
8. Circular linked lists can be used to represent a buffer of audio or signal data
in signal processing applications. The last node is connected to the first node
to create a loop, and the processing algorithms can efficiently iterate over the
data.
9. Traffic light control systems use circular linked lists to manage the traffic
light cycles. Each phase of the traffic light cycle is represented as a node in
the list, and the last node is connected to the first node to create a loop.
Application of Doubly Linked Lists:
1. Redo and undo functionality.
2. Use of the Back and forward button in a browser.
3. The most recently used section is represented by the Doubly Linked list.
4. Other Data structures like Stack, Hash Table, and Binary Tree can also be
applied by Doubly Linked List.
5. Used to implement game objects and their interactions in a game engine.
6. Used in networking.
7. Used in Graph algorithms.
8. Operating systems use doubly linked lists to manage the process scheduling.
Each process waiting to be executed is represented as a node in the doubly
linked list, and the operating system can easily traverse the list in both
directions to manage the process queue.
➢ Polynomial representation Using Linked List

Each node of a linked list representing polynomial constitute three parts:

o The first part contains the value of the coefficient of the term.
o The second part contains the value of the exponent.
o The third part, LINK points to the next term (next node).

The structure of a node of a linked list that represents a polynomial is shown below:

Consider a polynomial P(x) = 7x2 + 15x3 - 2 x2 + 9. Here 7, 15, -2, and 9 are the coefficients, and
4,3,2,0 are the exponents of the terms in the polynomial. On representing this polynomial using a
linked list, we have

Observe that the number of nodes equals the number of terms in the polynomial. So we have 4
nodes. Moreover, the terms are stored to decrease exponents in the linked list. Such representation
of polynomial using linked lists makes the operations like subtraction, addition, multiplication,
etc., on polynomial very easy.

1. Addition of Polynomials:
To add two polynomials, we traverse the list P and Q. We take corresponding terms of the list P
and Q and compare their exponents. If the two exponents are equal, the coefficients are added to
create a new coefficient. If the new coefficient is equal to 0, then the term is dropped, and if it is
not zero, it is inserted at the end of the new linked list containing the resulting polynomial. If one
of the exponents is larger than the other, the corresponding term is immediately placed into the
new linked list, and the term with the smaller exponent is held to be compared with the next term
from the other list. If one list ends before the other, the rest of the terms of the longer list is inserted
at the end of the new linked list containing the resulting polynomial.

Let us consider an example an example to show how the addition of two polynomials is performed,

P(x) = 3x4 + 2x3 - 4 x2 + 7

Q (x) = 5x3 + 4 x2 - 5

These polynomials are represented using a linked list in order of decreasing exponents as follows:

To generate a new linked list for the resulting polynomials that is formed on the addition of given
polynomials P(x) and Q(x), we perform the following steps,

1. Traverse the two lists P and Q and examine all the nodes.
2. We compare the exponents of the corresponding terms of two polynomials. The first term
of polynomials P and Q contain exponents 4 and 3, respectively. Since the exponent of the
first term of the polynomial P is greater than the other polynomial Q, the term having a
larger exponent is inserted into the new list. The new list initially looks as shown below:

3. We then compare the exponent of the next term of the list P with the exponents of the
present term of list Q. Since the two exponents are equal, so their coefficients are added
and appended to the new list as follows:

4. Then we move to the next term of P and Q lists and compare their exponents. Since
exponents of both these terms are equal and after addition of their coefficients, we get 0,
so the term is dropped, and no node is appended to the new list after this,

5. Moving to the next term of the two lists, P and Q, we find that the corresponding terms
have the same exponents equal to 0. We add their coefficients and append them to the new
list for the resulting polynomial as shown below:

Polynomial Multiplication:

You might also like