Week 2 (Singaly Link List)
Week 2 (Singaly Link List)
CLO:
02
Objectives:
To write a program that implements the basic operations of the linked list in C++.
Figure 1. Node
It is a linear data structure, in which the elements are not stored at contiguous memory
locations. The elements in a linked list are linked using pointers as shown in the below image:
✔ List is a collection of components, called nodes. Every node (except the last node)
contains the address of the next node. Every node in a linked list has two components:
⮚ One to store the relevant information (that is, data)
⮚ One to store the address, called the link or next, of the next node in the list.
✔ The address of the first node in the list is stored in a separate location, called the head
or first.
✔ The address of the last node in the list is stored in a separate location, called the tail or
last.
There are 3 types of linked list:
Singly Linked List
Circular Linked List
Doubly Linked List
In this lab we will discuss singly linked list.
Singly linked list:
Sample Code:
LinkList () {
head = NULL;
}
void display(){
if(head == NULL){
cout<<"List is empty"<<endl;
}
else{
Node *temp = head;
while(temp != NULL){
cout<<temp->data<<"\t";
temp=temp->next;
}
}
}
};
int main(){
LinkList L;
L.insertHead(20);
L.insertHead(30);
L.insertHead(40);
L.insertHead(50);
L.display();
}
LAB TASKS
As you have learned how to insert and delete a node at different positions in the link list now
you are required to perform the following tasks.
Suppose we have the following singly linked list
10 11 12 13
15 5 20 13 21 NULL
11 12
1. Create your own class of link list which will have the following functions.
a. Function called InsertAtBegin to add node at the begging of list.
After insertion of value 12 at the beginning of the linked list, it will become as following:
Start=9
9 10 11 12 13
12 15 5 20 21
10 11 12 13 NULL
10 11 12 13 14
NULL
15 5 20 13 21 25
11 12 14
10 11 12 13
15 5 20 13 21 NULL
11 12
If we want to update the value 20 residing at location 12 to 25, our linked list will display as
figure 6.
10 11 12 13
15 5 25 13 21 NULL
11 12
10 11 12 13
15 5 20 13 21 NULL
11 12