Topic:Linked List
lec 3 and 4
Topics to be Covered
⮚Linked List
⮚What’s Wrong with Array & Why Linked List?
⮚Why do we need linked lists?
⮚Operations of linked list
⮚Types of Linked list
⮚Applications of Linked List
Introduction-Linked List
• Data structure where data elements are arranged sequentially or linearly
where the elements are attached to its previous and next adjacent in
what is called a linear data structure.
• Data structures where data elements are not arranged sequentially or
linearly are called a non- linear data structure.
What’s Wrong with Array & Why Linked List?
Disadvantages Of Array:
• Slow searching in unordered array.
• Insertion and deletion operations are slow. Because, we have to shift
subsequent elements.
• Fixed size
• Wastage of memory
Linked list solve some of these problems:
• Linked list is able to grow in size as needed.
• Does not require shifting when performing insertion and deletion
operation.
• No wastage of memory
Why we need Linked List?
Why do we need linked lists?
What are Linked list?
• Structure to store a data similar to train.
Representation of a linked list
• Elements are not stored at contiguous memory locations.
• Elements in a link list are linked using pointers.
The first node in the sequence is termed as ‘head’. And we can identify the last node as the
one which points to ‘Null’.
Each node consists of -
• A data field
• Reference to the next node
Example: Maintaining Records using Linked List
Example-Student List
class Node {
public:
Student data;
int marks;
Node* next;
Node(const string& n, const string& e, int m) : data{ n, e }, marks(m),
next(nullptr) {}
};
class Student{
public:
string name;
string enroll;
};
class List {
public:
Node* head;
List() : head(nullptr) {}
void addNode(const string& name, const string& enroll, int marks) {
Node* newNode = new Node(name, enroll, marks);
newNode->next = head;
head = newNode;
}
};
#include <iostream>
using namespace std;
class Node {public:
//Student data;
string name;
string enroll;
int marks;
Node* next;
Node(const string& n, const string& e, int m)
{
name= n;
enroll = e;
marks = m;
next=nullptr;
}
class List {public: Node* head;
List() : head(nullptr) {}
void addNode(const string& name, const string& enroll, int
marks)
{
Node* newNode = new Node(name, enroll, marks);
newNode->next = head;
head = newNode;
}
};
int main() {
List studentList;
// Adding students to the list studentList.addNode("Ali",
"01-234123-001", 85);
studentList.addNode("Bilal", "01-234123-002", 92);
studentList.addNode("Amir", "01-234123-003", 78);
// Displaying the list
Node* current = studentList.head;
while (current) {
cout << "Name: " << current->name << ", Enrollment: " <<
current->enroll << ", Marks: " << current->marks << endl;
current = current->next; }
return 0;
}
Example-Student List
int main() {
List studentList;
// Adding students to the list
studentList.addNode("Ali", "01-234123-001", 85);
studentList.addNode("Bilal", "01-234123-002", 92);
studentList.addNode("Amir", "01-234123-003", 78);
// Displaying the list
Node* current = studentList.head;
while (current) {
cout << "Name: " << current->data.name << ", Enrollment: " << current-
>data.enroll << ", Marks: " << current->marks << endl;
current = current->next;
}
return 0;
}
Output-Student List
Name: Amir, Enrollment: 01-234123-003, Marks: 78
Name: Bilal, Enrollment: 01-234123-002, Marks: 92
Name: Ali, Enrollment: 01-234123-001, Marks: 85
we have perform only addition operation in this code. we can perform deletion,
searching and another operation by adding additional members functions in
program.
Operations-Linked List
The operations performed on the Linked List are as follows:
1. Creation
2. Insertion
3. Deletion
4. Traversing
5. Searching
6. Concatenation
Operation- Creation
Creation operation is used to create a node or
linked list. When a linked list is created with one
node, an insertion operation is used to add more
elements to the node.
There are three ways to insert a new node in
Linked List
● At the front of the linked list
● After a given node.
● At the end of the linked list.
Insertion- At the beginning of the linked list
A linked list is shown below 2->4->6->8->10. If we want to add a new
node 1, as the first node of the list.
Thus the new linked list becomes 1->2->4->6->8->10.
Insertion- After the given Node
A node is given and we have to add a new node after the given node. In the below-
linked list a->b->c->d ->e, if we want to add a node f after node c then the linked
list will look as follows:
we check if the given node is present. If it’s present, we create a new node f.
Then we point the next pointer of node c to point to the new node f. The next
pointer of the node f now points to node d.
Insertion- At the end of the Linked List
we add a new node at the end of the linked list. Consider we have the linked list a-
>b->c->d->e and we need to add a node f to the end of the list. The linked list will
look as shown below after adding the node.
we create a new node f. Then the tail pointer pointing to null is pointed to f and
the next pointer of node f is pointed to null.
Operation-Deletion
Deleting a node from a linked list also involves various positions from where the
node can be deleted. We can delete the
1. First node,
2. Last node
3. Random kth node from the linked list.
After deletion, we need to adjust the next pointer and the other pointers in the
linked list appropriately so as to keep the linked list intact.
Deleting the first Node
Here we apply 2 steps:
1. Making the starter pointer point towards the 2nd node.
2. Deleting the first node using delete keyword
Deleting the last node
Here we apply 2 steps:
1. Making the second last node’s next pointer point to NULL.
2. Deleting the last node via delete keyword.
Deleting a particular node
• We make the next pointer of the node previous to the node being deleted , point
to the successor node of the node to be deleted and then delete the node using
delete keyword.
Operation-Traversing
we will apply 3 steps:
1. we created a separate new pointer that we’re naming here temp.
2. And now, we will transfer or assign the value kept at head i.e. 1000 to temp.
3. The head was pointing to the first node, the temp will also point to the first node.
In the beginning we are first checking whether the list is empty or not.
if head is pointing to NULL in the beginning then the list is empty. So we’ll print
“list is empty“.
If the list is not empty?
Operation-Traversing
Operation-Searching
These steps are followed if we want to search an element in the linked list:
1. Define syntax to create linked list.
2. Initialize the variables.
3. Create a function named makeList() to create the linked list.
4. Now create a function to display list that will be used to print the list when
required.
5. Now create a search function to search the element.
6. If element is present in the linked list print element found
7. Else print element is not present in the list.
operation-Searching
Operation-Concatenation:
Let us assume that the two linked lists are referenced by head1 and head2 respectively.
1. If the first linked list is empty then return head2.
2. If the second linked list is empty then return head1.
3. Store the address of the starting node of the first linked list in a pointer variable, say p.
4. Move the p to the last node of the linked list through simple linked list traversal technique.
1. Singly Linked List
2. Doubly Linked List
Types of Linked List:
Singly Linked List:
Every node contains some data and a pointer to the next node of
the same data type.We mean that the node stores the address of
the next node in sequence.
A singly linked list allows traversal of data only in one way.
Example
A singly linked list is a web browser's history. When
you browse the internet, your web browser keeps
track of the pages you visit in a history list. Each page
you visit can be represented as a node in the singly
linked list, where each node contains the URL of the
webpage and a pointer to the next webpage you
visited.
#include <iostream>
#include <string>
// Node structure for a webpage in the history list
struct WebPage {
std::string url;
WebPage* next;
};
// Class for the web browser's history (Singly Linked
List)
class BrowserHistory {
private:
WebPage* head;
public:
BrowserHistory() {
head = nullptr;
}
// Function to add a new webpage to the
history list
void addWebPage(const std::string& url) {
WebPage* newPage = new WebPage;
newPage->url = url;
newPage->next = nullptr;
if (head == nullptr) {
head = newPage;
} else {
newPage->next = head;
head = newPage;
}
}
// Function to display the web browser's history
void displayHistory() {
WebPage* temp = head;
int count = 1;
while (temp != nullptr) {
std::cout << count << ". " << temp->url <<
std::endl;
temp = temp->next;
count++;
}
std::cout << std::endl;
}
};
int main() {
BrowserHistory myHistory;
// Adding webpages to the history
myHistory.addWebPage("https://www.example.co
m/page1");
myHistory.addWebPage("https://www.example.co
m/page2");
myHistory.addWebPage("https://www.example.co
m/page3");
// Displaying the web browser's history
std::cout << "Web Browser History:" << std::endl;
myHistory.displayHistory();
return 0;
}
Output-Singly Linked List
Web Browser History:
1. https://www.example.com/page3
2. https://www.example.com/page2
3. https://www.example.com/page1
Doubly Linked List
In a doubly linked list, Each node contains a data part and two
addresses, one for the previous node and one for the next
node.
Example
A doubly linked list is a text editor's undo/redo
functionality. In a text editor, when you make changes
to a document (e.g., typing, deleting, formatting), the
editor stores these changes in a history list, allowing
you to undo or redo the changes you've made. Each
state of the document can be represented as a node in
the doubly linked list, where each node contains the
text content of the document at that state along with
two pointers: one pointing to the previous state
(undo) and another pointing to the next state (redo).
#include <iostream>
#include <string>
using namespace std;
// Node structure for a state in the text editor's history
class EditorState {
public:
std::string content;
EditorState* next;
EditorState* prev;
};
// Class for the text editor's history (Doubly Linked List)
class EditorHistory {
private:
EditorState* currentState;
public:
EditorHistory() {
currentState = nullptr;}
// Function to add a new state to the history
(undo operation)
void addState(const string& content)
{
EditorState* newState = new EditorState;
newState->content = content;
newState->next = nullptr;
if (currentState == nullptr)
{
newState->prev = nullptr;
}
else
{
newState->prev = currentState;
currentState->next = newState;
}
currentState = newState;
}
// Function to perform undo (move to the previous state)
bool undo() {
if (currentState == nullptr || currentState->prev ==
nullptr) {
return false; // Nothing to undo
}
currentState = currentState->prev;
return true;}
// Function to perform redo (move to the next state)
bool redo() {
if (currentState == nullptr || currentState->next ==
nullptr) {
return false; // Nothing to redo
}
currentState = currentState->next;
return true;
}
// Function to display the current state
(content)
void displayCurrentState() {
if (currentState == nullptr)
{
cout << "Text editor is empty." <<
endl;
}
else
{
cout << "Current content:" << endl;
cout << currentState->content << endl;
}
}
};
int main() {
EditorHistory myEditor;
// Initial state (empty document)
myEditor.addState("");
// Typing some content
myEditor.addState("Hello, ");
myEditor.addState("Hello, world!");
// Display current content
myEditor.displayCurrentState();
// Perform undo and display content
myEditor.undo();
myEditor.displayCurrentState();
// Perform redo and display content
myEditor.redo();
myEditor.displayCurrentState();
return 0;
}
Output:
Current content:
Hello, world!
Current content:
Hello,
Current content:
Hello, world!
Application of doubly linked list:
1. Represent a deck of cards in game.
2. undo and redo operations in text editors.
3. A music player which has next and previous button uses doubly linked list.
Application of Linked List in real world
1. Image Viewer.
2. Previous and next page in web browser
3. Music Player
Application of Linked list in computer science:
1. Implementation of stacks and queues.
2. Implementation of graphs.
3. Dynamic memory allocation.
4. Managing Directory of names
Overflow
Sometimes data are inserted into data structure but there is no
available space.
Example: In linked lsit overflow occur when
1. Avail = NULL and
2. There is an insertion operation
Underflow:
want to delete data from data structure that is empty.
Example:In linked list overflow occurs when:
• START=NULL and
• There is an deletion operation

Lec3-Linked list.pptx

  • 1.
  • 2.
    Topics to beCovered ⮚Linked List ⮚What’s Wrong with Array & Why Linked List? ⮚Why do we need linked lists? ⮚Operations of linked list ⮚Types of Linked list ⮚Applications of Linked List
  • 3.
    Introduction-Linked List • Datastructure where data elements are arranged sequentially or linearly where the elements are attached to its previous and next adjacent in what is called a linear data structure. • Data structures where data elements are not arranged sequentially or linearly are called a non- linear data structure.
  • 4.
    What’s Wrong withArray & Why Linked List? Disadvantages Of Array: • Slow searching in unordered array. • Insertion and deletion operations are slow. Because, we have to shift subsequent elements. • Fixed size • Wastage of memory
  • 5.
    Linked list solvesome of these problems: • Linked list is able to grow in size as needed. • Does not require shifting when performing insertion and deletion operation. • No wastage of memory Why we need Linked List?
  • 6.
    Why do weneed linked lists?
  • 7.
    What are Linkedlist? • Structure to store a data similar to train.
  • 8.
    Representation of alinked list • Elements are not stored at contiguous memory locations. • Elements in a link list are linked using pointers. The first node in the sequence is termed as ‘head’. And we can identify the last node as the one which points to ‘Null’. Each node consists of - • A data field • Reference to the next node
  • 9.
  • 10.
    Example-Student List class Node{ public: Student data; int marks; Node* next; Node(const string& n, const string& e, int m) : data{ n, e }, marks(m), next(nullptr) {} }; class Student{ public: string name; string enroll; }; class List { public: Node* head; List() : head(nullptr) {} void addNode(const string& name, const string& enroll, int marks) { Node* newNode = new Node(name, enroll, marks); newNode->next = head; head = newNode; } };
  • 11.
    #include <iostream> using namespacestd; class Node {public: //Student data; string name; string enroll; int marks; Node* next; Node(const string& n, const string& e, int m) { name= n; enroll = e; marks = m; next=nullptr; } class List {public: Node* head; List() : head(nullptr) {} void addNode(const string& name, const string& enroll, int marks) { Node* newNode = new Node(name, enroll, marks); newNode->next = head; head = newNode; } }; int main() { List studentList; // Adding students to the list studentList.addNode("Ali", "01-234123-001", 85); studentList.addNode("Bilal", "01-234123-002", 92); studentList.addNode("Amir", "01-234123-003", 78); // Displaying the list Node* current = studentList.head; while (current) { cout << "Name: " << current->name << ", Enrollment: " << current->enroll << ", Marks: " << current->marks << endl; current = current->next; } return 0; }
  • 12.
    Example-Student List int main(){ List studentList; // Adding students to the list studentList.addNode("Ali", "01-234123-001", 85); studentList.addNode("Bilal", "01-234123-002", 92); studentList.addNode("Amir", "01-234123-003", 78); // Displaying the list Node* current = studentList.head; while (current) { cout << "Name: " << current->data.name << ", Enrollment: " << current- >data.enroll << ", Marks: " << current->marks << endl; current = current->next; } return 0; }
  • 13.
    Output-Student List Name: Amir,Enrollment: 01-234123-003, Marks: 78 Name: Bilal, Enrollment: 01-234123-002, Marks: 92 Name: Ali, Enrollment: 01-234123-001, Marks: 85 we have perform only addition operation in this code. we can perform deletion, searching and another operation by adding additional members functions in program.
  • 14.
    Operations-Linked List The operationsperformed on the Linked List are as follows: 1. Creation 2. Insertion 3. Deletion 4. Traversing 5. Searching 6. Concatenation
  • 15.
    Operation- Creation Creation operationis used to create a node or linked list. When a linked list is created with one node, an insertion operation is used to add more elements to the node. There are three ways to insert a new node in Linked List ● At the front of the linked list ● After a given node. ● At the end of the linked list.
  • 16.
    Insertion- At thebeginning of the linked list A linked list is shown below 2->4->6->8->10. If we want to add a new node 1, as the first node of the list. Thus the new linked list becomes 1->2->4->6->8->10.
  • 17.
    Insertion- After thegiven Node A node is given and we have to add a new node after the given node. In the below- linked list a->b->c->d ->e, if we want to add a node f after node c then the linked list will look as follows: we check if the given node is present. If it’s present, we create a new node f. Then we point the next pointer of node c to point to the new node f. The next pointer of the node f now points to node d.
  • 18.
    Insertion- At theend of the Linked List we add a new node at the end of the linked list. Consider we have the linked list a- >b->c->d->e and we need to add a node f to the end of the list. The linked list will look as shown below after adding the node. we create a new node f. Then the tail pointer pointing to null is pointed to f and the next pointer of node f is pointed to null.
  • 19.
    Operation-Deletion Deleting a nodefrom a linked list also involves various positions from where the node can be deleted. We can delete the 1. First node, 2. Last node 3. Random kth node from the linked list. After deletion, we need to adjust the next pointer and the other pointers in the linked list appropriately so as to keep the linked list intact.
  • 20.
    Deleting the firstNode Here we apply 2 steps: 1. Making the starter pointer point towards the 2nd node. 2. Deleting the first node using delete keyword
  • 21.
    Deleting the lastnode Here we apply 2 steps: 1. Making the second last node’s next pointer point to NULL. 2. Deleting the last node via delete keyword.
  • 22.
    Deleting a particularnode • We make the next pointer of the node previous to the node being deleted , point to the successor node of the node to be deleted and then delete the node using delete keyword.
  • 23.
    Operation-Traversing we will apply3 steps: 1. we created a separate new pointer that we’re naming here temp. 2. And now, we will transfer or assign the value kept at head i.e. 1000 to temp. 3. The head was pointing to the first node, the temp will also point to the first node.
  • 24.
    In the beginningwe are first checking whether the list is empty or not. if head is pointing to NULL in the beginning then the list is empty. So we’ll print “list is empty“. If the list is not empty? Operation-Traversing
  • 26.
  • 27.
    These steps arefollowed if we want to search an element in the linked list: 1. Define syntax to create linked list. 2. Initialize the variables. 3. Create a function named makeList() to create the linked list. 4. Now create a function to display list that will be used to print the list when required. 5. Now create a search function to search the element. 6. If element is present in the linked list print element found 7. Else print element is not present in the list. operation-Searching
  • 28.
    Operation-Concatenation: Let us assumethat the two linked lists are referenced by head1 and head2 respectively. 1. If the first linked list is empty then return head2. 2. If the second linked list is empty then return head1. 3. Store the address of the starting node of the first linked list in a pointer variable, say p. 4. Move the p to the last node of the linked list through simple linked list traversal technique.
  • 29.
    1. Singly LinkedList 2. Doubly Linked List Types of Linked List:
  • 30.
    Singly Linked List: Everynode contains some data and a pointer to the next node of the same data type.We mean that the node stores the address of the next node in sequence. A singly linked list allows traversal of data only in one way.
  • 31.
    Example A singly linkedlist is a web browser's history. When you browse the internet, your web browser keeps track of the pages you visit in a history list. Each page you visit can be represented as a node in the singly linked list, where each node contains the URL of the webpage and a pointer to the next webpage you visited.
  • 32.
    #include <iostream> #include <string> //Node structure for a webpage in the history list struct WebPage { std::string url; WebPage* next; }; // Class for the web browser's history (Singly Linked List) class BrowserHistory { private: WebPage* head; public: BrowserHistory() { head = nullptr; } // Function to add a new webpage to the history list void addWebPage(const std::string& url) { WebPage* newPage = new WebPage; newPage->url = url; newPage->next = nullptr; if (head == nullptr) { head = newPage; } else { newPage->next = head; head = newPage; } }
  • 33.
    // Function todisplay the web browser's history void displayHistory() { WebPage* temp = head; int count = 1; while (temp != nullptr) { std::cout << count << ". " << temp->url << std::endl; temp = temp->next; count++; } std::cout << std::endl; } }; int main() { BrowserHistory myHistory; // Adding webpages to the history myHistory.addWebPage("https://www.example.co m/page1"); myHistory.addWebPage("https://www.example.co m/page2"); myHistory.addWebPage("https://www.example.co m/page3"); // Displaying the web browser's history std::cout << "Web Browser History:" << std::endl; myHistory.displayHistory(); return 0; }
  • 34.
    Output-Singly Linked List WebBrowser History: 1. https://www.example.com/page3 2. https://www.example.com/page2 3. https://www.example.com/page1
  • 35.
    Doubly Linked List Ina doubly linked list, Each node contains a data part and two addresses, one for the previous node and one for the next node.
  • 36.
    Example A doubly linkedlist is a text editor's undo/redo functionality. In a text editor, when you make changes to a document (e.g., typing, deleting, formatting), the editor stores these changes in a history list, allowing you to undo or redo the changes you've made. Each state of the document can be represented as a node in the doubly linked list, where each node contains the text content of the document at that state along with two pointers: one pointing to the previous state (undo) and another pointing to the next state (redo).
  • 37.
    #include <iostream> #include <string> usingnamespace std; // Node structure for a state in the text editor's history class EditorState { public: std::string content; EditorState* next; EditorState* prev; }; // Class for the text editor's history (Doubly Linked List) class EditorHistory { private: EditorState* currentState; public: EditorHistory() { currentState = nullptr;} // Function to add a new state to the history (undo operation) void addState(const string& content) { EditorState* newState = new EditorState; newState->content = content; newState->next = nullptr; if (currentState == nullptr) { newState->prev = nullptr; } else { newState->prev = currentState; currentState->next = newState; } currentState = newState; }
  • 38.
    // Function toperform undo (move to the previous state) bool undo() { if (currentState == nullptr || currentState->prev == nullptr) { return false; // Nothing to undo } currentState = currentState->prev; return true;} // Function to perform redo (move to the next state) bool redo() { if (currentState == nullptr || currentState->next == nullptr) { return false; // Nothing to redo } currentState = currentState->next; return true; } // Function to display the current state (content) void displayCurrentState() { if (currentState == nullptr) { cout << "Text editor is empty." << endl; } else { cout << "Current content:" << endl; cout << currentState->content << endl; } } };
  • 39.
    int main() { EditorHistorymyEditor; // Initial state (empty document) myEditor.addState(""); // Typing some content myEditor.addState("Hello, "); myEditor.addState("Hello, world!"); // Display current content myEditor.displayCurrentState(); // Perform undo and display content myEditor.undo(); myEditor.displayCurrentState(); // Perform redo and display content myEditor.redo(); myEditor.displayCurrentState(); return 0; } Output: Current content: Hello, world! Current content: Hello, Current content: Hello, world!
  • 40.
    Application of doublylinked list: 1. Represent a deck of cards in game. 2. undo and redo operations in text editors. 3. A music player which has next and previous button uses doubly linked list.
  • 41.
    Application of LinkedList in real world 1. Image Viewer. 2. Previous and next page in web browser 3. Music Player
  • 42.
    Application of Linkedlist in computer science: 1. Implementation of stacks and queues. 2. Implementation of graphs. 3. Dynamic memory allocation. 4. Managing Directory of names
  • 43.
    Overflow Sometimes data areinserted into data structure but there is no available space. Example: In linked lsit overflow occur when 1. Avail = NULL and 2. There is an insertion operation
  • 44.
    Underflow: want to deletedata from data structure that is empty. Example:In linked list overflow occurs when: • START=NULL and • There is an deletion operation