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

Chapter 3 Linked List

Review on Pointer and Dynamic Memory allocation Singly Linked List and Its Implementation Doubly Linked List and Its Implementation Circular Linked Lists and Its

Uploaded by

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

Chapter 3 Linked List

Review on Pointer and Dynamic Memory allocation Singly Linked List and Its Implementation Doubly Linked List and Its Implementation Circular Linked Lists and Its

Uploaded by

Bedasa Wayessa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

Course Title: Data Structure & Algorithm.

Credit Hour: 3 hrs.


Course Code: CoSc2091.
ECTS: 5 [2 Lecture hours and 3 Lab hours]
Lecture Schedule: Every ____________

Bedasa Wayessa
[email protected]

Data Structures and Algorithms - CoSc2091 1


Classroom Rules
• Late comer will only tolerated for the first 5 minutes of every class
• Talk to me and Not to each other
• Do not sleep
• Do not use phones
• Fail to obey the Classroom rule  face 2  3 class ban

Data Structures and Algorithms - CoSc2091 2


Assignment Submission
 Guidelines for submission will be provided with every assignment
 Re-grade requests will ONLY be entertained within one week after
the assignments have been handed back to students or assignment due
date
 IMPORTANT: Late submissions are allowed ONLY until 1 day following
the deadline, with 10% marks deduction.
 IMPORTANT: Late + Copy = ZERO Marking

Data Structures and Algorithms - CoSc2091 3


QUIZZES
• Quizzes will NOT be announced
• Re-grade requests will only be entertained within one week after the
marked quizzes have been handed back to students [with tangible and
acceptable reason only]

Data Structures and Algorithms - CoSc2091 4


Introduction to Data Structure and
Algorithms

LinkedList

Data Structures and Algorithms - CoSc2091 5


Outlines
 Review on Pointer and Dynamic Memory allocation
 Singly Linked List and Its Implementation
 Doubly Linked List and Its Implementation
 Circular Linked Lists and Its

Data Structures and Algorithms - CoSc2091 6


Review on Pointer
 In C++, pointers are variables that store the memory addresses of other
variables.
 Address in C++ : & it is a addresses operator in C++.
 If we have a variable var in our program, &var will give us its address in
the memory.
 For Example: // declare variables
int var1 = 3; // print address of var1
cout << "Address of var1: "<< &var1 << endl;
Output: Address of var1: 0x7fff5fbff8ac
 Note: You may not get the same results when you run the program

Data Structures and Algorithms - CoSc2091 7


Review on Pointer
 C++ Pointers: Pointers are used to store addresses rather than values.
 Here is how we can declare pointers.
 Syntax:
type *ptr;
type * ptr;
type* ptr;
 Note: The * operator is used after the data type to declare pointers.
 We can also declare pointers in the following way.
int* pointVar; // preferred syntax
int* pointVar, p; //Here, we have declared a pointer pointVar and
// a normal variable p.

Data Structures and Algorithms - CoSc2091 8


Review on Pointer
 Get the Value from the Address Using Pointers
 To get the value pointed by a pointer, we use the * operator.
 For example:
int var = 5;
int* pointVar = &var; // assign address of var to pointVar

cout<< *pointVar << endl; // access value pointed by pointVar


//Output: 5

 In the above code:-


– var is an integer variable which holds the value 5.
– the address of var is assigned to pointVar.
– the *pointVar to get the value stored in that address.

Data Structures and Algorithms - CoSc2091 9


Review on Pointer
 Get the Value from the Address Using Pointers
 In the above code:
 Using * (asterisk) operator, we can access the value stored at the
pointer.
 When * is used with pointers, it's called the dereference operator.
 It operates on a pointer and gives the value pointed by the address
stored in the pointer.
 That is, *pointVar = var.
 Note: In C++, pointVar and *pointVar is completely different.
 We cannot do something like *pointVar = &var;

Data Structures and Algorithms - CoSc2091 10


Dynamic Memory allocation
 When we run a C++ program on our machine, it requires some space
to store its instructions (statements), local variables, global variables, and
various other functions in C++.
 This space required to run a C++ Program is known as memory in
computers.
 There are two types of memory :- Static Memory and Dynamic Memory.
 Static Memory Allocation:
– It is a constant space allocated by the operating system during the
compile time of a C++ program and it internally uses stack data
structure to manage the static memory allocation.
– We can't reallocate the space consumed by the program until its
execution is over.

Data Structures and Algorithms - CoSc2091 11


Dynamic Memory allocation
 Dynamic Memory Allocation:
– DMA is the process of assigning the memory space during the
execution time or the run time.
– DMA is allocated on Heap and non-static and local variables get
memory allocated on Stack.
– new and delete Operators in C++ for Dynamic Memory
– You can create objects dynamically in a heap using the new operator.
– pointer-variable = new data-type;

– Initialize memory: int *p = new int(25);


– Allocate block of memory: int *p = new int[10];
– delete Operator: delete pointer-variable;

Data Structures and Algorithms - CoSc2091 12


Dynamic Memory allocation
 General Memory Layout • c

 The layout consists of a lot of


segments, including:
 stack: stores local variables
 heap: dynamic memory for
programmer to allocate
 data: stores global variables,
separated into initialized and
uninitialized
 text: stores the code being
executed

Data Structures and Algorithms - CoSc2091 13


Dynamic Memory allocation
 Exam static & Dynamically
declaration

Heap
int main(){
int A[4]
int A[4] == {1,
{1,2,
2,3,3,4};
4}
A 1 2 3 4 p Stack
int *p;
pp == new
new int[4];
int[4];
}

Data Structures and Algorithms - CoSc2091 14


Dynamic Memory allocation
 General Memory Layout • c

 The layout consists of a lot of


segments, including:
 stack: stores local variables
 heap: dynamic memory for
programmer to allocate
 data: stores global variables,
separated into initialized and
uninitialized
 text: stores the code being
executed

Data Structures and Algorithms - CoSc2091 15


Introduction - LinkedList
 The linked list is a non-primitive and linear data structure.
 A linked list is a collection of objects linked together by references
from one object to another object.
 A linked list is a linear dynamic data structure to store data items.
 We also know that arrays are a linear data structure that store data
items in contiguous memory locations.
 Unlike arrays, the linked list does not store data items in contiguous
memory locations.
 A linked list consists of items/objects called “Nodes” which contain two
parts.
 The first part stores the actual data and
 The second part has a pointer that points to the next node.

Data Structures and Algorithms - CoSc2091 16


Introduction - LinkedList
 linked list or single linked list is a sequence of elements in which every
element has link to its next element in the sequence.
 This structure is usually called “Singly linked list”.
Head Tail


N1 next N2 next N3 next null

Node1 Node2 Node3

 The first node of the linked list is called “head” while the last node is
called “Tail”.
 The last node of the linked list will have its next pointer as NULL
since it will not have any memory address pointed to.

Data Structures and Algorithms - CoSc2091 17


Introduction - LinkedList
 Since each node has a pointer to the next node, data items in the
linked list need not be stored at contiguous locations.
 The nodes can be scattered in the memory.
 We can create a Node data type in C++, as follows:

class Node {
public:
int value;
Node * Next;
};

 We will also use the following diagram to represent a single node:


value Next

Data Structures and Algorithms - CoSc2091 18


Introduction - LinkedList
 Now, let's create three single nodes using our new Node data type.
 The nodes will contain the values 7, 14, and 21 for each node.
 The code should be as follows:
//display all create Node.
Node * node1 = new Node();
void PrintNode(Node * node){
node1->Value = 7; while(node != NULL) {
Node * node2 = new Node(); cout << node->Value;
node2->Value = 14; node = node->Next;
}
Node * node3 = new Node(); cout << "NULL" << endl;
node3->Value = 21; }

 Note that, since we don't initialize the Next pointer for all nodes, it will
be automatically filled with the null pointer (NULL).
7 NULL 14 NULL 21 NULL

Data Structures and Algorithms - CoSc2091 19


Introduction - LinkedList
 It's time to connect the preceding three nodes so that it becomes a node
chain. We will:
– set the Next pointer of node1 to the node2 object,
– set the Next pointer of node2 to the node3 object, and
– keep the Next pointer of node3 remaining NULL to indicate that it's
the end of the chain.
– The code will be as follows:
node1->Next = node2;
node2->Next = node3;
– By executing the preceding code snippet

7  14  21 NULL

Data Structures and Algorithms - CoSc2091 20


Introduction - LinkedList
 To display all the Linked List Node:
void PrintNode(Node * node){

// It will print the initial node


// until it finds NULL for the Next pointer
// that indicate the end of the node chain
while(node != NULL) {
cout << node->Value << " -> ";
node = node->Next;
}
cout << "NULL" << endl;
}

7 next  14 next  21 NULL

Data Structures and Algorithms - CoSc2091 21


LinkedList Basic Operations
• Following are the basic operations supported by a list
– Insertion:
 Adds an element at the beginning of the list.
 After the given Node.
 At the end of the Linked List
– Deletion:
 Deletes an element at the beginning of the list.
 Random kth the given Node.
 From the last node of the Linked List
– Display − Displays the complete list.
– Search − Searches an element using the given key
– Count − Counts an element in the given List.

Data Structures and Algorithms - CoSc2091 22


LinkedList Basic Operations
• Few important Operation:
• Let say: head tail


Node *head, *tail; 7  14  Null
• We can define these
tail = head
tail = head->next
head = head->next
• If head has no pointer it is a null or 0.
• To check whether pointer is pointing to next Node
If (head->next != Null){}

Data Structures and Algorithms - CoSc2091 23


Why Linked Lists
• Linked lists are widely used in many applications because of the
flexibility it provides.
• Unlike arrays that are dynamically assigned, linked lists do not require
memory from a contiguous block.
• This makes it very appealing to store data in a linked list, when the data
set is large or device has limited memory.
• One of the disadvantages of linked lists is that they are not random
accessed like arrays.
• To find information in a linked list one must start from the head of the
list and traverse the list sequentially until it finds (or not find) the node.
• Another advantage of linked lists over arrays is that when a node is
inserted or deleted, there is no need to “adjust” the array.

Data Structures and Algorithms - CoSc2091 24


Types of LinkedList
• The link list are of Four types such as:
– Single Link List
– Double Link List
– Circular Link List

Types Details

Single Link List • SLL contains only one link for each node which points to the
next link and therefore can navigate only forward direction.

Double Link List • DLL contains two link for each node.
• The 1st link points to the previous node and the 2nd link
points to the next link.
• Therefore can navigate in bot direction.
Circular Link List • CLL the last node contains link next, which points to the
value field of the 1st node and the 1st node link field has a link
as previous, which points to the last node value field.
Data Structures and Algorithms - CoSc2091 25
Singly Linked List
– The Singly Linked List (also known as the linked list) is a sequence of
items linked with each other.
– It's actually a chaining of nodes, where each node contains the item's
value and the next pointer.
– In other words, each item in the linked list has a link to its next item in
the sequence.
– Traversal is allowed only one way and there is no going back.
– The thing that differs between the linked list and the node chain is
that the linked list has a Head and a Tail pointer.
– The Head informs the first item and the Tail informs the last item in
the linked list.

Data Structures and Algorithms - CoSc2091 26


Singly Linked List
– Representation of a Singly Linked List:
– A Singly Linked List can be represented using a linked data structure.
– In this structure, each node contains two fields:
– Data: This field stores the value of the node.
– Link: Contains the memory address of the next node in the list.
– In C++ Node can be created using a class.
• The first node in the list is called the
class Node {
public: head node, and it contains the memory
int value; address of the second node.
Node * Next;
}; • The last node in the list has a null value
in the link field, indicating the end of
value Next
the list.
Data Structures and Algorithms - CoSc2091 27
Singly Linked List(SLL)
– Uses of Singly Linked List:
– Singly Linked List data structure is commonly used in situations
where data needs to be stored and accessed in a sequential manner,
but the size of the data is not known in advance.
– Advantages and Disadvantages of Singly Linked List
– Dynamic size: The size of a linked list can be changed dynamically,
unlike arrays, which have a fixed size.
– Easy insertion and deletion: SLL allows easy insertion and
deletion of nodes, as only the pointers need to be modified.
– Efficient memory utilization: SLL allows efficient memory
utilization as nodes can be allocated as needed.

Data Structures and Algorithms - CoSc2091 28


Singly Linked List(SLL)
– Insertion Operations:
1. Add a Node in a Singly Linked List:
– To add a node to a Singly Linked List, we first create a new node and
assign its data field with the value we want to store.
– We then update the link field of the new node to point to the
current head node, and update the head node to point to the new
node.
Insert at the beginning
void addNode(int value) { • Allocate memory for new node
Node *newNode = new Node(); • Store data
newNode->data = value; • Change next of new node to
newNode->next = head; point to head
• Change head to point to recently
head = newNode; created node
}
7 NULL  14 NULL  21 NULL
Data Structures and Algorithms - CoSc2091 29
Singly Linked List(SLL)
– Insertion Operations:
2. Add a Node At the End in a Singly Linked List:
 Algorithm
1. Declare head pointer and make it as NULL.
2. Create a new node with the given data.
• And make the new node => next as NULL.
• (Because the new node is going to be the last node.)
3. If the head node is NULL (Empty Linked List),
• make the new node as the head.
4. If the head node is not null, (Linked list already has some elements),
• find the last node.
• make the last node => next as the new node.

Data Structures and Algorithms - CoSc2091 30


Singly Linked List(SLL)
– Insertion Operations:
2. Add a Node At the End in a Singly Linked List:
void SLinkedList::insertAtEnd(int x){
Node * newNode = new Node();
newNode->data = x; Insert at the End
newNode->next = NULL; • Allocate memory for new
/* If the Linked List is empty, node
set the head to the new node */ • Store data
• Traverse to last node
if (head == NULL) {
• Change next of last node
head = newNode; to recently created node
return;
}
// Traverse to the end of the Linked List
Node * current = head;
while(current->next != NULL){
current = current->next;
}
current->next = newNode; 7 NULL  14 NULL  21 NULL
}
Data Structures and Algorithms - CoSc2091 31
Singly Linked List(SLL)
– Insertion Operations:
3. Add a node after a given Position:
• To add a node after a given position in a singly linked list in C++, you can
follow the below steps:
– Traverse the linked list until the desired position is reached.
– Allocate memory for the new node and assign its data value.
– Set the next pointer of the new node to the next of the current node.
– Point the next pointer of the current node to the new node.

7 NULL  14 NULL  21 NULL

Data Structures and Algorithms - CoSc2091 32


Singly Linked List(SLL)
– Insertion Operations:
3. Add a node after a given Position:
void SLinkedList::insertAfter(int index, int x){
//Create a Node to be Inserted
Node * newNode = new Node();
//Assign a Give Value to Node
newNode->data = x;
newNode->next = NULL;
//Create a new Node ptr to find a position
Node * current = head;
for (int i = 0; i < index - 1; i++){
current = current->next;
}
//Now move up to given index
newNode->next = current->next;
current->next = newNode;
}
}

Data Structures and Algorithms - CoSc2091 33


Singly Linked List(SLL)
– Insertion Operations:
3. Add a node at given Position in singly Linked List:
1. Create a new node with the given data.
2. If the given index is less than 0:
• Print an error message and return, as the index is invalid.
3. If the given index is 0:
a. Make the new node the new head of the list.
b. Set the next pointer of the new node to point to the current head.
c. Update the head pointer to point to the new node.
4. Otherwise:
a. Start from the head of the list and traverse to the node at index - 1.
b. If the index is out of range (i.e., there are fewer than index nodes in the list):
• Print an error message and return, as the index is invalid.
c. Insert the new node between the current node at index - 1 and its next
node:
• Set the next pointer of the new node to point to the next node of the
current node.
• Set the next pointer of the current node to point to the new node.

Data Structures and Algorithms - CoSc2091 34


Singly Linked List(SLL)
– Insertion Operations:
3. Add a node at given Position in singly Linked List:
void SLinkedList::insertAtIndex(int index, int x){
//Create a Node to be Inserted
Node * newNode = new Node();
//Assign a Give Value to Node
newNode->data = x;
//Check wether Index < 0
if(index < 0){
cout<<" Invalid Position!\n";
return;
}
if(index == 0){
newNode->next = head;
head = newNode;
return;
}

Data Structures and Algorithms - CoSc2091 35


Singly Linked List(SLL)
– Insertion Operations:
3. Add a node a given Position:
//Create a new Node ptr to find a position
Node * current = head;
for (int i = 0; i < index-1 && current; ++i){
current = current->next;
}
if(!current){
cout<<index<< " Is invalid position!";
return;
}
//Now move up to given index
newNode->next = current->next;
current->next = newNode;
}

Data Structures and Algorithms - CoSc2091 36


Singly Linked List(SLL)
– Common Singly Linked List Operations:
4. Traverse a Singly Linked List:
– To traverse a Singly Linked List, we start at the head node and
follow the link field of each node until we reach the end of the list
(the node with a null pointer).
void traverse() {
Node *current = head;
while (current != NULL) {
cout<<current->data<<" -> ";
current = current->next;
}
}

Data Structures and Algorithms - CoSc2091 37


Singly Linked List(SLL)
– Common Singly Linked List Operations:
5. Search an Element in Singly Linked List:
– To search for an element in a Singly Linked List, we start at the head
node and traverse the list until we find the node with the desired
value, or reach the end of the list.
bool search(int value) {
Node *current = head;
while (current != NULL) {
if (current->data == value) {
return true;
}
current = current->next;
}
return false;
}
Data Structures and Algorithms - CoSc2091 38
Singly Linked List(SLL)
– Delete Operations:
6. Delete a Node from a Singly Linked List:
– Delete from beginning
– Point head to the second node

head = head->next;
head

7 NULL 14 NULL  21 NULL

Data Structures and Algorithms - CoSc2091 39


Singly Linked List(SLL)
– Delete Operations:
6. Delete a Node from a Singly Linked List:
– Delete from end
Node * temp = head;
while(temp->next->next != NULL){
temp = temp->next;
Delete from end
}
• Traverse to second last element
temp->next = NULL; • Change its next pointer to null
temp

7 NULL  14 NULL 21 NULL

Data Structures and Algorithms - CoSc2091 40


Singly Linked List(SLL)
– Delete Operations:
6. Delete a Node from a Singly Linked List:
– Delete from some position
deletefrom(int position){
Node * temp = head;
for(int i = 2; i < position; i++) {
if(temp->next != NULL) {
temp = temp->next; Delete from middle
• Traverse to element before
}
the element to be deleted
}
• Change next pointers to
temp->next = temp->next->next; exclude the node from the
} chain

7 NULL 7 NULL 7 NULL

Data Structures and Algorithms - CoSc2091 41


Singly Linked List(SLL)
– Delete Operations:
6. Delete a Node from a Singly Linked List:
– To delete a node from a Singly Linked List, we need to find the node to
delete and update the link field of the previous node to point to the
next node. We then free the memory of the deleted node.
void deleteNode(int value) {
Node *current = head;
Node *previous = NULL;

// Traverse the list to find the node to delete


while (current != NULL && current->data != value) {
previous = current;
current = current->next;
}
Data Structures and Algorithms - CoSc2091 42
Singly Linked List(SLL)
– Delete Operations:
6. Delete a Node from a Singly Linked List:
// If the node to delete is found, update the link
field of the previous node
if (current != NULL) {
if (previous == NULL) {
head = current->next;
} else {
previous->next = current->next;
}
free(current);
}
}

Data Structures and Algorithms - CoSc2091 43


Singly Linked List(SLL): Example 1
– Common Singly Linked List Operations: Complete program
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node * next;
};
class SLinkedList {
public:
Node * head;
SLinkedList();
SLinkedList(int x);
//Node * addNode(int data);
void display();
void isEmpty();
void insertAtEnd(int x);
};
Data Structures and Algorithms - CoSc2091 44
Singly Linked List(SLL): Example 1
– Common Singly Linked List Operations: Complete program
SLinkedList::SLinkedList(){
head = tail = NULL;
}
SLinkedList::SLinkedList(int x){
head = new Node();
Node * root = new Node();
root->data = x;
root->next = NULL;
head = root;
}
void SLinkedList::isEmpty(){
//Node * root = head;
if(head == NULL){
cout<<"Linked List is Empty!. \n";
}
}
Data Structures and Algorithms - CoSc2091 45
Singly Linked List(SLL): Example 1
– Common Singly Linked List Operations: Complete program
void SLinkedList::insertAtEnd(int x){
Node * newNode = new Node();
newNode->data = x;
newNode->next = NULL;
/* If the Linked List is empty,
set the head to the new node */
if (head == NULL) {
head = newNode;
return;
}
// Traverse to the end of the Linked List
Node * current = head;
while(current->next != NULL){
current = current->next;
}
current->next = newNode;
}

Data Structures and Algorithms - CoSc2091 46


Singly Linked List(SLL): Example 1
– Common Singly Linked List Operations: Complete program
void SLinkedList::display(){
Node * root = head;
if(head == NULL){
cout<<"\nLinked List is Empty!. \n";
}else{
while(root != NULL){
cout<<" "<<root->data<<" -> ";
root = root->next;
}
}
cout<<"Null\n";
}

Data Structures and Algorithms - CoSc2091 47


Singly Linked List(SLL): Example 1
– Common Singly Linked List Operations: Complete program
int main(int argc, char** argv) {
SLinkedList s0;
SLinkedList sl(9);
//insert
sl.insertAtEnd(10);
sl.insertAtEnd(11);
//display
sl.display();
return 0;
}

Output:
9 -> 10 -> 11 -> Null

--------------------------------

Data Structures and Algorithms - CoSc2091 48


Singly Linked List(SLL): Example 2
– Common Singly Linked List Operations: Complete program
class LinkedList{
#include <iostream> private:
using namespace std; Node* head = NULL;
class Node{ public:
public: void addNode(int value) {
Node *newNode = new Node();
int data;
newNode->data = value;
Node * next; newNode->next = head;
}; head = newNode;
int main(){ }
LinkedList ls; void traverse() {
ls.addNode(3); Node *current = head;
ls.addNode(7); while (current != NULL) {
cout<<current->data<<" -> ";
cout<<"Linked List: "; current = current->next;
ls.traverse(); }
return 0; cout<<"NULL\n";
} }
};
Data Structures and Algorithms - CoSc2091 49
Singly Linked List(SLL): Example 3
– Common Singly Linked List Operations: Complete program
class Node {
public:
int data;
Node *next;
};
class LinkedList {
private: Note: read c++ scope
Node *first; resolution.
public:
LinkedList() { – implement all this
first = NULL; operation using
}
LinkedList(int A[], int n);
scope resolution in
~LinkedList(); c++.
void display();
void insert(int index, int x);
int deletes(int index);
int length();
}; Data Structures and Algorithms - CoSc2091 50
Singly Linked List(SLL): Example 2
– Common Singly Linked List Operations: Complete program
1. Create list of node from an arrays of data structure.
LinkedList::LinkedList(int A[], int n) {
Node *last, *t;
int i = 0;
first = new Node;
first->data = A[0]; Note: read cpp scope
first->next = NULL; resolution(::).
last = first;
for (i = 1; i < n; i++) { – implement all this
t = new Node(); operation using
t->data = A[i]; scope resolution in
t->next = NULL;
cpp.
last->next = t;
last = t;
}
}

Data Structures and Algorithms - CoSc2091 51


Singly Linked List(SLL): Example 2
– Common Singly Linked List Operations: Complete program
2. Delete a node from an list Linked List Node data structure.

LinkedList::~LinkedList() {
Node *p = first;
while (first) {
first = first->next; Note: read cpp scope
delete p; resolution(::).
p = first;
}
– implement all this
}
operation using
scope resolution in
cpp.

Data Structures and Algorithms - CoSc2091 52


Singly Linked List(SLL): Example 2
– Common Singly Linked List Operations: Complete program
3. Display all node from an list Linked List Node data structure.
void LinkedList::display() {
Node *p = first;
while (p) {
cout << p->data << " "; Note: read cpp scope
p = p->next;
resolution(::).
}
cout << endl;
– implement all this
}
operation using
scope resolution in
cpp.

Data Structures and Algorithms - CoSc2091 53


Singly Linked List(SLL): Example 2
– Common Singly Linked List Operations: Complete program
4. Count all node from an list Linked List Node data structure.
int LinkedList::length() {
Node *p = first;
int len = 0;
Note: read cpp scope
while (p) { resolution(::).
len++;
p = p->next;
– implement all this
}
operation using
return len;
scope resolution in
}
cpp.

Data Structures and Algorithms - CoSc2091 54


Singly Linked List(SLL): Example 2
– Common Singly Linked List Operations: Complete program
5. Insert node to an list Linked List at in given index data structure.
void LinkedList::insert(int index, int x){
Node *t, *p = first;
if (index < 0 || index > length()) Note: read cpp
return;
t = new Node();
scope
t->data = x; resolution(::).
t->next = NULL;
if (index == 0) { – implement all
t->next = first; this operation
first = t; using scope
} else {
for (int i = 0; i < index - 1; i++)
resolution in
p = p->next; cpp.
t->next = p->next;
p->next = t;
}
}
Data Structures and Algorithms - CoSc2091 55
Singly Linked List(SLL): Example 2
– Common Singly Linked List Operations: Complete program
6. Delete node from an list Linked List at in given index data structure.
int LinkedList::deletes(int index) {
Node *p, *q = NULL;
int x = -1;
if (index < 1 || index > length())
return -1;
if (index == 1) {
p = first;
first = first->next;
x = p->data;
delete p;
}

Data Structures and Algorithms - CoSc2091 56


Singly Linked List(SLL): Example 2
– Common Singly Linked List Operations: Complete program
6. Delete node from an list Linked List at in given index data structure.

else {
p = first;
for (int i = 0; i < index - 1; i++) {
q = p;
p = p->next;
}
q->next = p->next;
x = p->data;
delete p;
}
return x;
}

Data Structures and Algorithms - CoSc2091 57


Singly Linked List(SLL): Example 2
– Common Singly Linked List Operations: Complete program
– Finally call it from main method.
int main() {
//created array Output:
int A[] = { 1, 2, 3, 4, 5 }; The created LinkedList are:
//create an object 1 -> NULL
LinkedList l(A, 5); 1 -> 2 -> NULL
//inser value at index 3 1 -> 2 -> 3 -> NULL
l.insert(3, 10); 1 -> 2 -> 3 -> 4 -> NULL
1 -> 2 -> 3 -> 10 -> 4 -> 5 -> NULL
//display all Node
l.display(); Total Node: 6
return 0; --------------------------------
}

Data Structures and Algorithms - CoSc2091 58


Doubly Linked List
– A Doubly linked list is a data structure that consists of a set of
sequentially linked nodes, each containing two links:
– One to the next node and another to the previous node.
– This allows for traversal in both forward and backward directions,
making it different from a singly linked list, which only allows for
traversal in one direction.
– Representation of a Doubly Linked List:
– A Doubly Linked List is represented by a series of nodes, where each
node contains three fields.
– Data: Stores the value of the node.
– Previous: A pointer that stores the address of the previous node.
– Next: A pointer that stores the address of the next node.

Data Structures and Algorithms - CoSc2091 59


Doubly Linked List
– Uses of Doubly Linked List:
– Implementing undo/redo functionality in text editors and graphic design
applications.
– Implementing navigation in web browsers, where the back and forward
buttons allow for traversal in both directions.
– Advantages of Doubly Linked List
– Allows for traversal in both forward and backward directions.
– Insertion and deletion of nodes are efficient.
– Can be used to implement stack, queue, and deque data structures.
– Disadvantages of Doubly Linked List
– Extra space is required for the previous pointers, increasing the memory
requirements. Implementation is more complex than a singly linked list.
Data Structures and Algorithms - CoSc2091 60
Doubly Linked List
– Representation of a Doubly Linked List:
class Node {
public:
int data;
Node * prev;
Node * next;
}; Head Tail


 
prev data next prev data next prev data next
 
Node1 Node2 Node3
class DoublyLinkedList {
public:
Node* head;
DoublyLinkedList(int data);
void addNodeHead(int data);
void addNodeEnd(int data);
};
Data Structures and Algorithms - CoSc2091 61
Doubly Linked List
– Representation of a Doubly Linked List:

class DoublyLinkedList {
public:
Node* head;
DoublyLinkedList(int data);
void addNodeHead(int data);
void addNodeEnd(int data);
};

// Constructor to initialize the doubly linked list


DoublyLinkedList::DoublyLinkedList(int x) {
head = new Node(); // Create a new node for the head
head->data = x; // Assign the data value
head->prev = NULL;
head->next = NULL;
}
Data Structures and Algorithms - CoSc2091 62
Doubly Linked List
– Common Doubly Linked List Operations
1. Add a New Node at head in a Doubly Linked List
– Create a new node and set its data value.
– Set the next pointer of the new node to the current head (which
becomes the new node’s next).
– Set the previous pointer of the new node to null (since it’s the new head).
– Update the previous pointer of the current head (if it exists) to point to
the new node.
Before Insertion:
┌─────────┐ ┌─────────┐ ┌─────────┐
│ Node A │ <───> │ Current │ <───> │ Node B │
└─────────┘ └─────────┘ └─────────┘
After Insertion (at Head):
┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐
│ NewNode │ <───> │ Node A │ <───> │ Current │ <───> │ Node B │
└─────────┘ └─────────┘ └─────────┘ └─────────┘
Data Structures and Algorithms - CoSc2091 63
Doubly Linked List
– Common Doubly Linked List Operations
1. Add a New Node at head in a Doubly Linked List
//Function to add a node as the head of the doubly linked list
void DoublyLinkedList::addNodeHead(int data) {
Node* newNode = new Node();
newNode->data = data;
newNode->prev = nullptr;
newNode->next = nullptr;
if (head == nullptr) {
head = newNode;
} else {
newNode->next = head;
head->prev = newNode;
head = newNode;
}
}

Data Structures and Algorithms - CoSc2091 64


Doubly Linked List
– Common Doubly Linked List Operations
2. Add a New Node at End in a Doubly Linked List
1. Create a new node with the given data.
2. If head is nullptr:
• Make the new node the head of the doubly linked list.
Else:
• Traverse the doubly linked list until the last node.
• Set the next pointer of the last node to point to the new node.
• Set the previous pointer of the new node to point to the last node.
3. Update the new node as the new last node.

Data Structures and Algorithms - CoSc2091 65


Doubly Linked List
– Common Doubly Linked List Operations
2. Add a New Node at End in a Doubly Linked List
//Function to add a node to the end of the doubly linked list
void DoublyLinkedList::addNodeEnd(int data) {
Node* newNode = new Node();
newNode->data = data;
newNode->prev = nullptr;
newNode->next = nullptr;
if (head == nullptr) {
head = newNode;
} else {
Node* current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = newNode;
newNode->prev = current;
}
}
Data Structures and Algorithms - CoSc2091 66
Doubly Linked List
– Common Doubly Linked List Operations
3. Count number of Node in a Doubly Linked List
– An algorithm to get the size of a doubly linked list:

1. Initialize a variable size to 0.


2. Start from the head of the doubly linked list.
3. Traverse the list while the current node is not nullptr:
a. Increment the size by 1.
b. Move to the next node.
4. Return the size as the number of nodes in the doubly linked list.

Data Structures and Algorithms - CoSc2091 67


Doubly Linked List
– Common Doubly Linked List Operations
3. Count number of Node in a Doubly Linked List
– An algorithm to get the size of a doubly linked list:
//Function to get the size of the doubly linked list
int DoublyLinkedList::getSize() {
int size = 0;
Node* current = head;

while (current != nullptr) {


size++;
current = current->next;
}
return size;
}

Data Structures and Algorithms - CoSc2091 68


Doubly Linked List
– Common Doubly Linked List Operations
4. Add Node at a Given Index in a Doubly Linked List

1. Get the size of the doubly linked list.


2. If the given index is negative, print an error message and return.
3. If the given index is greater than the size of the list, print an error
message and return.
4. Create a new node with the given data.
5. If the index is 0 or the list is empty, insert the new node at the beginning
of the list.
6. Otherwise, traverse the list to find the node at the (index - 1) position.
7. Insert the new node after the node found at (index - 1), updating the
pointers of the surrounding nodes.
Data Structures and Algorithms - CoSc2091 69
Doubly Linked List
– Common Doubly Linked List Operations
4. Add Node at a Given Index in a Doubly Linked List
//At a given index in the doubly linked list
void DoublyLinkedList::addNodeAtIndex(int index, int data){
int size = getSize();
if (index < 0) {
cout << "Index cannot be negative." << endl;
return;
} else if (index > size) {
cout << "Index is out of range." << endl;
return;
}
Node* newNode = new Node();
newNode->data = data;

Data Structures and Algorithms - CoSc2091 70


Doubly Linked List
– Common Doubly Linked List Operations
if (index == 0 || head == nullptr) {
// Insert at the beginning
newNode->next = head;
if (head != nullptr){
head->prev = newNode;
}
head = newNode; // Update head to point to the new node
} else {
Node* current = head;
for (int i = 0; i < index - 1; ++i) {
current = current->next;
}
newNode->next = current->next;
if (current->next != nullptr){
current->next->prev = newNode;
}
current->next = newNode;
newNode->prev = current;
}
} Data Structures and Algorithms - CoSc2091 71
Doubly Linked List
– Common Doubly Linked List Operations
5. Add Traverse a Doubly Linked List
1. Start from the head of the doubly linked list.
2. While the current node is not nullptr:
a. Process the data of the current node (e.g., print it).
b. Move to the next node.
3. End traversal when you reach the last node (nullptr).
void DoublyLinkedList::displayList() {
Node* current = head;
while (current != nullptr) {
cout << current->data << " <=> ";
current = current->next;
}
cout << "\n";
}
Data Structures and Algorithms - CoSc2091 72
Doubly Linked List
– Common Doubly Linked List Operations
3. Delete a Node from Doubly Linked List
– To delete a node from the Doubly Linked List, we need to follow the
following steps:
– If the node to be deleted is not the head node, then set the next
pointer of the previous node of the node to be deleted to the next
node of the node to be deleted.
– If the node to be deleted is not the last node, then set the previous
pointer of the next node of the node to be deleted to the previous
node of the node to be deleted.
– Free the memory of the node to be deleted.

Data Structures and Algorithms - CoSc2091 73


Doubly Linked List
– Common Doubly Linked List Operations
• Prepare a Node

class Node {
public:
int data; prev data next
Node * prev;
Node1
Node * next;
};

Data Structures and Algorithms - CoSc2091 74


Doubly Linked List
– Common Doubly Linked List Operations
• Doubly Linked List at Head
class DLL{
public: Head Tail


Node * head;
Node * tail; 
prev data next prev data next
DLL(); 
DLL(int x); Node1 Node2
void fdisplay();
void bdisplay();
void addAtEnd(int x);
void addAtHead(int x);
void insertAtIndex(int pos, int x);
int m_count;

};

Data Structures and Algorithms - CoSc2091 75


Doubly Linked List
– Common Doubly Linked List Operations
• Doubly Linked List at default constructor
DLL::DLL(){
head = NULL; //set empty ptr
tail = NULL; //set empty ptr
}
//create node with a give Dll constructor as head
//and at the same time head & tail pointing to same

DLL::DLL(int x){
head = new Node(); //new Node
head->data = x; //set data to the node
head->next = NULL; //next ptr is null
head->prev = NULL; //prev ptr is null
tail = head; //since 1 node tail&head
m_count++;
}
Data Structures and Algorithms - CoSc2091 76
Doubly Linked List
– Common Doubly Linked List Operations
1. Add a Node in a Doubly Linked List at Head
void DLL::addAtHead(int x){
Node *temp = new Node(); //create temp Node
temp->data = x; //assign data to it

if (head == NULL){ // if no node before assign


head = temp; // new to as head
return;
}
head->prev = temp; //else put temp node to the
temp->next = head; //next ptr of head
head = temp;
m_count++; //created node count variable
}

Data Structures and Algorithms - CoSc2091 77


Doubly Linked List
– Common Doubly Linked List Operations
2. Add a Node in a Doubly Linked List at TAIL

void DLL::addAtEnd(int x){


Node *temp = new Node(); //create a new node
temp->data = x; //assign data to it
tail->next = temp; // assign next ptr of tail
temp->prev = tail; // to current Node
tail = temp; // then assign temp to tait
m_count++;
}

Data Structures and Algorithms - CoSc2091 78


Doubly Linked List
– Common Doubly Linked List Operations
3. Add a Node at given position of List
void DLL::insertAtIndex(int pos, int x){
if(pos == 0){ //if 0 index it is head
addAtHead(x);
return;
}
if(pos == m_count){ // last index it is Tail
addAtEnd(x);
return;
}
if (pos > m_count){ // given value is out of index
cout<< pos <<" : This Index is Out of Index!\n";
}

Data Structures and Algorithms - CoSc2091 79


Doubly Linked List
– Common Doubly Linked List Operations
3. Add a Node at given position of List

Node *temp = head;


for(int i = 0; i < pos-1; i++){
temp = temp->next; //moves ptr to given pos
}
Node * nextNode = temp->next; //assign next ptr
Node * node = new Node(); // create new node
node->data = x; // assign value to it
node->next = nextNode; // assign prev node
node->prev = temp;
temp->next = node;
nextNode->prev = node;
m_count++;
}

Data Structures and Algorithms - CoSc2091 80


Doubly Linked List
– Common Doubly Linked List Operations
4. Display Node in a Doubly Linked List:
void DLL::fdisplay(){
cout<<"Forward Traversal Display:\n";
Node * temp = head;
while(temp != NULL){
cout<<" "<<temp->data<<" ";
temp = temp->next;
}
cout<<"\n";
}
void DLL::bdisplay(){
cout<<"Backward Traversal Display:\n";
Node * temp = tail;
while(temp != NULL){
cout<<" "<<temp->data<<" ";
temp = temp->prev;
}
cout<<"\n";
}
Data Structures and Algorithms - CoSc2091 81
Doubly Linked List
– Common Doubly Linked List Operations
4. Finally call from main method Node in a Doubly Linked List:

int main(int argc, char** argv) {


DLL ls(10);
Output:
ls.addAtHead(1); Forward Traversal Display:
ls.addAtHead(2);
2 -> 1->10->90->91->100->99-> NULL
ls.addAtEnd(90);
ls.addAtEnd(91); Backward Traversal Display:
ls.insertAtIndex(5, 100); 99->100->91->90 ->10->1->2-> NULL
ls.addAtEnd(99);
ls.fdisplay(); --------------------------------
ls.bdisplay();
return 0;
}

Data Structures and Algorithms - CoSc2091 82


Circular Linked List
– A circular linked list is a data structure where each node contains a
reference to the next node in the list, and the last node in the list
points back to the first node.
– This creates a circular loop that can be traversed infinitely.
– In a singly linked list, the last node points to NULL, but in a circular
linked list, the last node points back to the first node.
– Uses of Circular Linked List:
– Circular linked lists are useful in situations where we need to
traverse a list indefinitely, for example in a circular buffer or a playlist
of songs that should loop indefinitely.

Data Structures and Algorithms - CoSc2091 83


Circular Linked List
– Representation of a Circular Linked List:
– A circular linked list can be represented as a collection of nodes, where
each node contains two fields: data and next.
– The data field contains the value of the node, and the next field
contains a reference to the next node in the list.
– The last node in the list contains a reference to the first node,
creating a circular loop.
Head Tail


data next  data next  data next
Node1 Node2 Node3

Data Structures and Algorithms - CoSc2091 84


Circular Linked List
– Advantages of Circular Linked List
– A circular linked list can be traversed indefinitely.
– Insertion and deletion operations can be performed efficiently at any
position in the list.
– Disadvantages of Circular Linked List
– It is more complex to implement than a singly linked list.
– It requires extra memory to store the reference from the last node
back to the first node.
Head Tail


data next  data next  data next
Node1 Node2 Node3

Data Structures and Algorithms - CoSc2091 85


Circular Linked List
– Example how to create Circular Linked List:
class Node{ int main(){
public: Node *n1 = new Node(10);
int data; Node *n2 = new Node(2);
Node * next; Node *n3 = new Node(6);
Node(int d){
// linking the nodes
data = d;
n1->next = n2;
}
n2->next = n3;
};
n3->next = n1;
Head Tail
Node* ptr = n1;

int k = 6;
10 next  2 next  6 next
while(k--){
Node1 Node2 Node3 cout<<ptr->data<<" -> ";
ptr = ptr->next;
}
Circular output: return 0;
10 -> 2 -> 6 -> 10 -> 2 -> 6 -> }
--------------------------------
Data Structures and Algorithms - CoSc2091 86
Assignment
• Work on:
– How to count number of Node in LinkedList with example?
– How to Search an Element in LinkedList with example?
– How to sort Elements of a Linked List with example?
– How to add data in LinkedList with example?

Data Structures and Algorithms - CoSc2091 87


Arrays Vs Linked Lists
 Arrays have fixed size  Linked list size is dynamic

 Insertion of new element is


 Insertion/deletion is easier
expensive

 Random access is allowed  Random access not possible

 Elements are at contiguous


 Elements have non-contiguous
location
location
 No extra space is required for  Extra memory space required for
the next pointer next pointer

• As arrays and linked lists are both used to store items and are linear data
structures, both these structures can be used in similar ways for most of
the applications.

Data Structures and Algorithms - CoSc2091 88


Quiz
• Write the advantage of Linked List over Array data structure

Data Structures and Algorithms - CoSc2091 89


End of LinkedList

Next: Stack Data Structure

Data Structures and Algorithms - CoSc2091 90

You might also like