0% found this document useful (0 votes)
11 views30 pages

5 Lecture DSOOP LinkedList DrTahirNawaz

The document provides an overview of linked lists, a dynamic data structure useful for storing data elements in non-contiguous memory blocks. It details the advantages of linked lists over arrays, such as easier insertion and deletion, and outlines the implementation of linked lists in C++ through classes and pointers. Additionally, it describes various operations that can be performed on linked lists, including insertion and deletion at different positions, and includes a quiz related to creating a bank account class.

Uploaded by

Sajid Ali
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)
11 views30 pages

5 Lecture DSOOP LinkedList DrTahirNawaz

The document provides an overview of linked lists, a dynamic data structure useful for storing data elements in non-contiguous memory blocks. It details the advantages of linked lists over arrays, such as easier insertion and deletion, and outlines the implementation of linked lists in C++ through classes and pointers. Additionally, it describes various operations that can be performed on linked lists, including insertion and deletion at different positions, and includes a quiz related to creating a bank account class.

Uploaded by

Sajid Ali
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/ 30

EC-204 Data Structures and Object

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.

• It is particularly useful when the data is dynamic in


nature and we do not know the number of data elements
beforehand.

• The prerequisite of understanding linked list is a working


knowledge of pointers and dynamic memory allocation
as they are both used in it’s implementation

• Data elements, belonging to a specific data type, are


stored in multiple non-contiguous blocks of memory.
Introduction (contd.)
• A linked list is made up of many nodes which are
connected in nature. Every node is mainly divided into
two parts, one part holds the data and the other part is
connected (linked) to a different node.

• Each node contains a data member (the left part of the


picture) and link (reference/address) to another node
(the right part of the picture).
• The head pointer points to the first node of a Linked List.
• Notice that the last node doesn’t point to any node and
just stores NULL, representing the end (tail) of the list
Advantages of using Linked Lists
• Consider an example of a contact list (arranged in
alphabetic order) in a cell phone. Suppose these
contacts are stored in a vector

Ali Chris James Maaz Sally Umar


0 1 2 3 4 5
• In order to insert an element (say Bob), there would be a
need to shift all of the following elements rightward.
Basically, in a vector, for an insertion, the amount of
work depends on the no. of contacts we have got
Bob

Ali Chris James Maaz Sally Umar


Advantages of using Linked Lists (contd.)
• In a linked list, each node is linked to another node
• The links are pointer containing addresses of next nodes

Ali Chris James Maaz Sally Umar

• In order to insert Bob node into the list, all we need to do


is to make Ali’s link to point to Bob and make Bob’s link
to point to Chris

Ali Chris James Maaz Sally Umar

Bob
Advantages of using Linked Lists (contd.)
• Linked List is a linear data structure like arrays

• Unlike arrays, linked list elements are not stored at


contiguous blocks of memory

• With arrays we must know the number of elements in


advance; so the allocated memory is equal to the upper
limit irrespective of the usage. The size of linked lists can
grow and shrink dynamically!

• Linked list enables an easy insertion and deletion of


elements (nodes)
Implementation of Linked List
• In C++, we achieve this functionality by using
classes/structures and pointers. Each class/structure
represents a node having some data and also a pointer
to another class/structure of the same kind. This pointer
holds the address of the next node and creates the link
between two nodes. So, the class/structure is something
like:

class node{ struct node


public: {
int v; int data;
node *next; node *next;
node(){ };
next = NULL;
}
};
Implementation of Linked List
• To fully achieve functionality, we need to able to perform
following six operations on a Linked List:
• Insert at Beginning
• Insert at End
• Insert at a given position
• Delete at Beginning
• Delete at End
• Delete at a given position
• Print Linked List

• Next we’ll code and discuss the above six operations


Implementation of Linked List
• Below is our LinkedList class containing a pointer
head that points to the first node of the linked list (that
also effectively stores its identity) and public member
functions which performs various operations.
class LinkedList{
node *head;
public:
LinkedList(){head=NULL;}
/* Member functions to perform
different operations on Linked List */
void insert_at_beignning(int v);
void insert_at_end(int v);
void insert_at_given_position(int v, int p);
void delete_at_beignning();
void delete_at_end();
void delete_at_given_position(int p);
void print(); };
Implementation of Linked List
1. Allocate a new node
2. Insert new element
3. Make new node point to old head
4. Update head to point to new node

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

one two three

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.

• Otherwise, store the address of the first node of the


linked list in temp.

• 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

void insert_at_given_position(int v, int p){


node *temp = new node;
temp->v = v;
if (p == 0){
// if p==0 then insert temp at beginning
temp->next = head;
head = temp;
}
Implementation of Linked List
Insert at a given position
else{
node *ptr = head;
// the loop sets ptr to (p-1)th node
while(p>1) {
ptr = ptr->next;
--p;}
// ptr now points to (p-1)th node
// insert temp between (p-1)th and
pth node
temp->next = ptr->next;
ptr->next = temp;
}
}
Implementation of Linked List
Insert at End
• The function accepts 1 argument that is the data we
want to insert at the end
• First, we allocate a block of memory to store the node
data
• Initialize a new node temp with value v.
• If the linked list is empty, simply make temp the new
head.
• If the linked list is not empty, move to the last node of the
linked list and set the next of the last node to temp.
Implementation of Linked List
Insert at End
void insert_at_end(int v){
node *temp = new node;
temp->v = v;
if (head == NULL){
head = temp;
}
else{
node *ptr = head;
while (ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = temp;
}
}
Caution!

• Always make sure


that your linked list
functions work
correctly with an
empty list.

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

//loop sets temp to last and temp1 to 2nd last node


while (temp->next != NULL) {
temp1 = temp;
temp = temp->next;
}
// temp now points to the last node of linked list
cout<<"Element Deleted: "<<temp->v<<endl;
// delete last node
delete temp;
// set the next of 2nd last node to NULL
temp1->next = NULL;
}
}
Implementation of Linked List
Delete at End
• If the list is empty, do nothing.

• If the linked list contains only 1 node, simply free the


head and set head to NULL.

• Otherwise, if the linked list contains more than 1 element,


move to the 2nd last element of the linked list. Free the
memory of the last node and set the next of 2nd last
element to NULL.
Implementation of Linked List
Delete at a given position

void delete_at_given_position(int p){


if (head == NULL){
// if list is empty do nothing
cout<<"List is Empty"<<endl;
}
else{
node *temp, *ptr;
if (p == 0) {
// if p==0, perform delete at beginning
cout<<"Element Deleted: "<<head->v<<endl;
ptr = head;
head = head->next;
delete ptr;
}
Implementation of Linked List
Delete at a given position
else{
// if p > 0
// set ptr to pth node and temp to (p-1)th node
ptr = head;
while(p>0){
--p;
temp = ptr;
ptr = ptr->next;
}
cout<<"Element Deleted: "<<ptr->v<<endl;
// set next of (p-1)th node to next of pth node
temp->next = ptr->next;
delete ptr; // free pth node
}
}
}
Implementation of Linked List
Delete at a given position
• The function accepts 1 argument p, that is the position of
node we want to delete.

• If the list is empty, do nothing.

• If p == 0, simply delete the first node.

• 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/

• Deital and Deital, “C++ How to Program”, Latest Edition

• Stroustrup, “Programming – Principles and Practice


Using C++”, Latest Edition
Quiz 5

• (Create a class called Account that a bank might use


to represent customers' bank accounts.
• Your class should include one data member of type
int to represent the account balance.
• Your class should provide a constructor that
receives an initial balance and uses it to initialize the
data member.
• The constructor should validate the initial balance to
ensure that it is greater than or equal to 0. If not, the
balance should be set to 0 and the constructor
should display an error message, indicating that the
initial balance was invalid.
• The class should provide three member functions.
Member function credit should add an amount to the
current balance.
• Member function debit should withdraw money from
the Account and should ensure that the debit
amount does not exceed the Account's balance. If it
does, the balance should be left unchanged and the
function should print a message indicating "Debit
amount exceeded account balance."
• Member function getBalance should return the
current balance. Create a program that creates two
Account objects and tests the member functions of
class Account.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy