5 Lecture DSOOP LinkedList DrTahirNawaz
5 Lecture DSOOP LinkedList DrTahirNawaz
Oriented Programming
Linked List
Dr Tahir Nawaz
Website: https://www.tahirnawaz.com
Email: tahir.nawaz@ceme.nust.edu.pk
Introduction
• Linked list is among the most important data structures.
Bob
Advantages of using Linked Lists (contd.)
• Linked List is a linear data structure like arrays
Insert at Beginning
void insert_at_beginning(int v)
{
node *temp = new node;
temp->v = v;
temp->next = head;
head = temp;
}
Traversing a SLL (animation)
temp
head
Linked Lists 11
Removing at the Head
1. Hold address of
head node in
temporary pointer
2. Update head to
point to next node in
the list
3. Delete the previous
head node whose
address is in
temporary node
Linked Lists 12
Implementation of Linked List
Delete at Beginning
void delete_at_beginning()
{
if (head == NULL){
cout<<"List is Empty"<<endl;
}
else{
cout<<"Element Deleted: "<<head->v<<endl;
node *temp = head;
head = head->next;
delete temp;
}
}
Implementation of Linked List
Delete at Beginning
• If the linked list is empty, do nothing.
• Then make the 2nd node of the linked list, that is head-
>next the new head. After that, free the old head (that
is temp).
Implementation of Linked List
Insert at a given position
• The function accepts 2 arguments. v is the data we need
to insert and p is the position where we want to insert v.
• First, we allocate a block of memory to store the node
data
• Initialize a new node temp with value v.
• If p == 0, then simply insert temp at beginning of the
linked list.
• If p > 0, move to the (p-1)th node and then insert
temp between (p-1)th and pth node.
Implementation of Linked List
Insert at a given position
EMPTY LIST
Implementation of Linked List
Delete at End
void delete_at_end(){
if (head == NULL){
cout<<"List is Empty"<<endl;
}
else if (head->next == NULL){
// if there's only 1 node in the linked list
// free head and set it to NULL
cout<<"Element Deleted: "<<head->v<<endl;
delete head;
head = NULL;
}
else{
// if there's more than 1 node in the linked
// traverse to the last and 2nd last nodes
node *temp = head; // to traverse to last node
node *temp1 = head;// to traverse to second node
Implementation of Linked List
Delete at End
• If p > 0,
• First set ptr to pth node and temp to (p-1)th node of the
linked list.
• Set temp->next to ptr->next.
• Delete ptr.
Implementation of Linked List
Print Linked List
void print(){
if (head == NULL){
cout<<"List is empty"<<endl;}
else{
node *temp = head;
cout<<"Linked List: ";
while (temp != NULL){
cout<<temp->v<<"->";
temp = temp->next; }
cout<<"NULL"<<endl;
}
}
• Simply traverse though all the nodes from head and
print the data
Acknowledgements/References
• https://slaystudy.com/singly-linked-list-program-in-c-
using-class/
• https://www.codesdope.com/blog/article/c-linked-lists-in-
c-singly-linked-list/