0% found this document useful (0 votes)
16 views21 pages

DS4 LinkedList

A linked list is a linear data structure consisting of nodes, where each node contains data and a pointer to the next node, allowing for dynamic memory allocation and efficient insertion and deletion. There are different types of linked lists, including singly linked lists, doubly linked lists, and circular linked lists, each with unique properties and implementations. Basic operations such as insertion, deletion, and traversal can be performed on linked lists, which can be implemented in C++ using structures and classes.

Uploaded by

kkr795707
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views21 pages

DS4 LinkedList

A linked list is a linear data structure consisting of nodes, where each node contains data and a pointer to the next node, allowing for dynamic memory allocation and efficient insertion and deletion. There are different types of linked lists, including singly linked lists, doubly linked lists, and circular linked lists, each with unique properties and implementations. Basic operations such as insertion, deletion, and traversal can be performed on linked lists, which can be implemented in C++ using structures and classes.

Uploaded by

kkr795707
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Linear Linked List


a linked list is a linear data structure that allows the users to store
data in non-contiguous memory locations. A linked list is defined
as a collection of nodes where each node consists of two members
which represents its value and a Link pointer which stores the
address for the next node. In this article, we will learn about the
linked list, its implementation, and its practical applications.

The elements of a linked list are called the nodes.


• A node has two fields i.e. data and Link.
•The data field contains the data being stored in that specific node.
It cannot just be a single variable. There may be many variables
presenting the data section of a node.
•The Link field contains the address of the next node. So this is the
place where the link between nodes is established.

fig1: structure of a node

fig2: linked list

Note: the down arrow in the last node indicates that this link field is
NULL. -the next pointer of the last node contains a special value,
called the NULL pointer, which does not point to any address of the
node. that is NULL pointer indicates the end of the linked list.
fig3: Linked list and values of the links

Representation of Linked List The Linked List can be represented


in memory in the following declaration(we need to declare each
node as class or struct).

struct node
{
int data ; //Instead of „data‟ we also use „info‟
node *link ; // Instead of „Next‟ we also use „Link‟
};

ADVANTAGES AND DISADVANTAGES


Linked list have many advantages and some of them are:
1. Linked list are dynamic data structure. That is, they can grow or
shrink during the execution of a program.
2. Efficient memory utilization: In linked list (or dynamic)
representation, memory is not pre-allocated. Memory is allocated
whenever it is required. And it is deallocated (or removed) when it
is not needed.
3. Insertion and deletion are easier and efficient. Linked list
provides flexibility in inserting a data item at a specified position
and deletion of a data item from the given position.
4. Many complex applications can be easily carried out with linked
list.
Linked list has following disadvantages
1. More memory: to store an integer number, a node with integer
data and address field is allocated. That is more memory space is
needed.
2. Access to an arbitrary data item is little bit cumbersome and also
time consuming.

Linked Lists: some properties

fig 4 : Linked list with four nodes

Suppose that current is a pointer of the same type as the pointer


head, then the statement:
current = head ; copies the value of head into current.

fig 5: linked list after the statement current = head ;

consider the statement current = current −>link ;


this statement copies the value current −>link ,which is 2800 ,into
current. Therefore ,after this statement executes ,current points to
the second node in the list .
fig 6 : linked list after the statement current = current −>link

Current 2800
Current −> info 92
Current −> link 1500
Current −> link −> info 63
head−> link −>link 1500
head−>link−>link−>info 63
head−>link−>link−>link 3600
head−>link−>link−>link−>info 45
current−> link −>link 3600

Operation on Linked List


The basic operations of a linked list are as follows: search the list
to determine whether a particular item in the list, insert an item in
the list, and delete an item from the list.these operations require
the list to be traversed(is the process of going through all the
nodes from one end to another end of a linked list . Concatenation
is the process of appending the second list to the end of the first
list.
We cannot use the pointer head to traverse the list because if we
use head to traverse the list, we would lose the nodes of the list.
We always want head to point to the first node, suppose that
current is a pointer of the same type. the following code traverses
the list :
current = head ;
while( current != NULL)
{ // process the current node
current = current −> link ; }

Example: the following code outputs the data stored in each node:

current = head ;
while( current != NULL)
{ cout<< current−> info << ” “ ;
current = current −> link ; }

Item insert and delete


Suppose that p points to the node with info 65, and new node with
info 50 is to be created and inserted after p .

fig 7 : link list before item insertion

struct node
{ int info;
node * link ; };
node *head , *p , *q ,*newNode;
newNode = new ; // create new
newNode −> info = 50 ; // store 50 in the new node

fig 8 : create newNode and store 50 in it


The following statements insert the node in the linked list at the required place:
newNode −>link = p −> link ;
p −> link = newNode ;

fig 9 :list after the statement newNode −>link = p −>link

After the second statement ( that is , p −> link = newNode ;), the
resulting list is as show in figure 10 .

Fig 10: Linked list after the statement p−> link = newNode

Deletion
consider the Linked list shown in figure 12 .

fig 12 : Node to be deleted is with info 34

We need pointer to this node (with info 34). the following statement
delete the node from the list and deallocate the memory occupied by
this node :
q = p −> link ;
p −> link = q −> link ;
delete q ;
Fig 13: list after the statement q = p −> link

Fig 14 : list after the statement p −> link = q −> link ;

Types of Linked Lists


Following are the types of linked lists :
1. Singly Linked List
The singly linked list is the simplest form of linked list in which the
node contain two members data and a next pointer that stores the
address of the next node. Each node is a singly linked list is
connected through the next pointer and the next pointer of the last
node points to NULL denoting the end of the linked list. The
following diagram describes the structure of a singly linked list:

2. Doubly Linked List


The doubly linked list is the modified version of the singly linked list
where each node of the doubly linked consists of three data
members data ,next and prev. The prev is a pointer that stores the
address of the previous node in the linked list sequence. Each node
in a doubly linked list except the first and the last node is connected
with each other through the prev and next pointer. The prev pointer
of the first node and the next pointer of the last node points to NULL
in the doubly linked list. The following diagram describes the
structure of a doubly linked list:

3. Circular Linked List


The circular linked list is almost same as the singly linked list but
with a small change. In a circular linked list the next pointer of the
last node points to the first node of the linked list rather than
pointing to NULL, this makes this data structure circular in nature
which is used in various applications like media players. The
following diagram describes the structure of a circular linked list:
Implementation of Linked List in C++
To implement a linked list in C++ we can follow the below
approach:
Approach:
 Define a structure Node having two members data and a link
pointer. The data will store the value of the node and the next
pointer will store the address of the next node in the sequence.
 Define a class LinkedList consisting of all the member
functions for the LinkedList and a head pointer that will store
the reference of a particular linked list.
 Initialize the head to NULL as the linked list is empty initially.
 Implement basic functions like insertAtBeginning,
insertAtEnd, deleteFromBeginning, deleteFromEnd that will
manipulate the elements of the linked list.
Representation of a Node in the Linked List
Each node of the linked list will be represented as
a structure having two members data and link where:
 Data: Represents the value stored in the node.
 Link Pointer: Stores the reference to the next node in the
sequence.
struct Node {
int data;
Node* link;
};
Basic Operations of a Linked List
Following are some basic operations that are required to
manipulate the nodes of a linked list:

Operation Description

Attaches a new node at the start of the


insertAtBeginning linked list.

Attaches a new node at the end of the


insertAtEnd linked list.

Attaches a new node at a specific


insertAtPosition position in the linked list.

Removes the Head of the linked list


and updates the Head to the next
deleteFromBeginning node.

Removes the node present at the end


deleteFromEnd of the linked list.

Removes a node from a given position


deleteFromPosition of the linked list.

Prints all the values of the nodes


Display present in the linked list.

Note: Here n denotes the number of nodes in the linked list.


Now let's learn how we can implement these basic functions of
linked list in C++:
Algorithm for insertAtBeginning Implementation
1. Create a new Node
2. Point the new Node's link pointer to the current head.
3. Update the head of the linked list as the new node.

Inserting a node at the first of the linked list

Algorithm for insertAtEnd Implementation


1. Create a new Node
2. If the linked list is empty, update the head as the new node.
3. Otherwise traverse till the last node of the linked list.
4. Update the link pointer of the last node from NULL to new
node.

Inserting a node at the end of the linked list

Algorithm for insertAtPosition Implementation


1. Check if the provided position by the user is a valid poistion.
2. Create a new node.
3. Find the node at position -1.
4. Update the next pointer of the new node to the next pointer of
the current node.
5. Update the link pointer of the current node to new node.
Inserting a node after the second position in the linked list

Algorithm for deleteFromBeginning Implementation


1. Check whether the Head of the linked list is not NULL. If Head
is equal to NULL return as the linked list is empty, there is no
node present for deletion.
2. Store the head of the linked list in a temp pointer.
3. Update the head of the linked list to next node.
4. Delete the temporary node stored in the temp pointer.

Deleting the first node of the linked list

Algorithm for deleteFromEnd Implementation


1. Verify whether the linked is empty or not before deletion.
2. If the linked list has only one node, delete head and set head
to NULL.
3. Traverse till the second last node of the linked list.
4. Store the last node of the linked list in a temp pointer.
5. Pointer the link pointer of the second last node to NULL.
6. Delete the node represented by the temp pointer.
Deleting the last node of the linked list

Algorithm for deleteFromPosition Implementation


1. Check if the provided postion by the users is a valid position in
the linked list or not.
2. Find the node at position -1.
3. Save node to be deleted in a temp pointer.
4. Set the link pointer of the current node to the next pointer of
the node to be deleted.
5. Set the link pointer of temp to NULL.
6. Delete the node represented by temp pointer.

Deleting the node present at the second position in the linked list

Algorithm for Display list contains Implementation


1. Check if the Head pointer of the linked list is not equal to
NULL.
2. Set a temp pointer to the Head of the linked list.
3. Until temp becomes null:
1. Print temp->data
2. Move temp to the next node.
C++ Program for Implementation of Linked List
The following program illustrates how we can implement a singly
linked list data structure in C++:

// C++ Program for Implementation of Single linked list

#include <iostream>
using namespace std;

// Structure for a node in the linked list


struct Node
{
int data;
Node* link;
};
Node* head = NULL;

// Function to Insert a new node at the beginning of the list


void insertAtBeginning(int value)
{
Node* newNode = new Node();
newNode->data = value;
newNode->link = head;
head = newNode;
}

// Function Insert a new node at the end of the list


void insertAtEnd(int value)
{
Node* newNode = new Node();
newNode->data = value;
newNode->link = NULL;
// If the list is empty, update the head to the new node
if (head == NULL)
{
head = newNode;
return;
}

// Traverse to the last node


Node* temp = head;
while (temp->link != NULL)
temp = temp->link;

// Update the last node's link to the new node


temp->link = newNode;
}

// Function to Insert a new node at a specific position in the list


void insertAtPosition(int value, int position)
{
if (position < 1) {
cout << "Position should be >= 1." << endl;
return;
}

if (position == 1) {
insertAtBeginning(value);
return;
}

Node* newNode = new Node();


newNode->data = value;
// Traverse to the node before the desired position
Node* temp = head;
for (int i = 1; i < position - 1 && temp !=NULL; ++i)
{
temp = temp->link;
}

// If the position is out of range, print an error message


if (temp ==NULL)
{
cout << "Position out of range." << endl;
delete newNode;
return;
}
// Insert the new node at the desired position
newNode->link = temp->link;
temp->link = newNode;
}

// Function to Delete the first node of the list


void deleteFromBeginning()
{
if (head==NULL)
{
cout << "List is empty." << endl;
return;
}
Node* temp = head;
head = head->link;
delete temp;
}
// Function to Delete the last node of the list
void deleteFromEnd()
{
if (head==NULL)
{
cout << "List is empty." << endl;
return;
}

if (head->link==NULL)
{
delete head;
head = NULL;
return;
}

// Traverse to the second-to-last node


Node* temp = head;
while (temp->link->link)
{
temp = temp->link;
}

// Delete the last node


delete temp->link;
// Set the second-to-last node's link to NULL
temp->link = NULL;
}
// Function to Delete a node at a specific position in the list
void deleteFromPosition(int position)
{
if (position < 1)
{
cout << "Position should be >= 1." << endl;
return;
}

if (position == 1)
{
deleteFromBeginning();
return;
}
Node* temp = head;
for (int i = 1; i < position - 1 && temp !=NULL; ++i)
{
temp = temp->link;
}

if ((temp==NULL) || (temp->link==NULL))
{
cout << "Position out of range." << endl;
return;
}
// Save the node to be deleted
Node* nodeToDelete = temp->link;
// Update the link pointer
temp->link = temp->link->link;
// Delete the node
delete nodeToDelete;
}
// Function to print the nodes value of the linked list
void display()
{
if (head==NULL)
{
cout << "List is empty." << endl;
return;
}

Node* temp = head;


while (temp !=NULL)
{
cout << temp->data << " -> ";
temp = temp->link;
}
cout << "NULL" << endl;
}

int main()
{
int x,p,k;

do
{
cout<<"=================================="<<endl;
cout<<"1) Insert element in the Begining"<<endl;
cout<<"2) Insert element in the End"<<endl;
cout<<"3) Insert element in the Position"<<endl;
cout<<"4) Delete element from the Begining"<<endl;
cout<<"5) Delete element from the End"<<endl;
cout<<"6) Delete element from the Position"<<endl;
cout<<"7) Display elements of the List"<<endl;
cout<<"0) Exit"<<endl;
cout<<"Enter your choice : ";
cin>>k;
switch (k)
{
case 1:{
cout<<"Enter value :";
cin>>x;
insertAtBeginning(x);
cout << "Linked list after insertions: ";
display();
break;
}
case 2:{
cout<<"Enter value :";
cin>>x;
insertAtEnd(x);
cout << "Linked list after insertions: ";
display();
break;
}
case 3:{
cout<<"Enter value :";
cin>>x;
cout<<"Enter position to insert :";
cin>>p;
insertAtPosition(x, p);
cout << "Linked list after insertions: ";
display();
break;
}
case 4:{
deleteFromBeginning();
cout << "Linked list after deleting : ";
display();
break;
}
case 5:{
deleteFromEnd();
cout << "Linked list after deleting : ";
display();
break;
}
case 6:{
cout<<"Enter position to delete :";
cin>>p;
deleteFromPosition(p);
cout << "Linked list after deleting : ";
display();
break;
}
case 7: display();
break;
case 8: cout<<"Exit"<<endl;
break;
default: cout<<"Invalid choice"<<endl;
}
} while( k != 0);

return 0;
}

You might also like