0% found this document useful (0 votes)
4 views73 pages

CSE 203 Week 3 - Single Linked Lists

Uploaded by

Imdadul Islam
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)
4 views73 pages

CSE 203 Week 3 - Single Linked Lists

Uploaded by

Imdadul Islam
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/ 73

Linked Lists

CSE 203 – Week 3


Lec Anika Ashraf
anikaashraf29@gmail.com

Lec Anika Ashraf, CSE Dept, MIST 1


Limitations of Dynamic Array
heap Memory (Horizontal View)
200

202
201

2
Limitations of Dynamic Array
heap Memory (Horizontal View)
200

202
201

•Memory Manager (A part of operating systems) manages


the memory.

•Keeps track of free space

•Allocates space on request from the programs


3
Limitations of Dynamic Array
heap Memory (Horizontal View)
200

202
201

Consider a program segment:

int *p=(int*)malloc(3*sizeof(int));

4
Limitations of Dynamic Array
heap Memory (Horizontal View)

212
200

202
201

p
Consider a program segment:
int *p=(int*)malloc(3*sizeof(int)); // int size is 4 bytes

5
Limitations of Dynamic Array
heap Memory (Horizontal View)

212
200

202
201

p
Consider a program segment:

int *p=(int*)malloc(3*sizeof(int)); // int size is 4 bytes


float *q=(float*)malloc(sizeof(float)); // float size is 8 bytes

6
Limitations of Dynamic Array
heap Memory (Horizontal View)

212
213

220
200

202
201

p q
Consider a program segment:

int *p=(int*)malloc(3*sizeof(int)); // int size is 4 bytes


float *q=(float*)malloc(sizeof(float)); // float size is 8 bytes

7
Limitations of Dynamic Array
heap Memory (Horizontal View)

212
213

220
200

202
201

p q
Consider a program segment:

int *p=(int*)malloc(3*sizeof(int)); // int size is 4 bytes


float *q=(float*)malloc(sizeof(float)); // float size is 8 bytes
int *r=(int*)malloc(4*sizeof(int)); // int size is 4 bytes

8
Limitations of Dynamic Array
heap Memory (Horizontal View)

212
213

220
200

202
201

p q
Consider a program segment:

int *p=(int*)malloc(3*sizeof(int)); // int size is 4 bytes


float *q=(float*)malloc(sizeof(float)); // float size is 8 bytes
int *r=(int*)malloc(4*sizeof(int)); // int size is 4 bytes

9
Limitations of Dynamic Array
heap Memory (Horizontal View)

236
212
213

220
221
200

202
201

p q r
Consider a program segment:
int *p=(int*)malloc(3*sizeof(int)); // int size is 4 bytes
float *q=(float*)malloc(sizeof(float)); // float size is 8 bytes
int *r=(int*)malloc(4*sizeof(int)); // int size is 4 bytes

10
Limitations of Dynamic Array
heap Memory (Horizontal View)

236
212
213

220
221
200

202
201

p q r
Consider a program segment:
int *p=(int*)malloc(3*sizeof(int)); // int size is 4 bytes
float *q=(float*)malloc(sizeof(float)); // float size is 8 bytes
int *r=(int*)malloc(4*sizeof(int)); // int size is 4 bytes
free(q)

11
Limitations of Dynamic Array
heap Memory (Horizontal View)

236
212
213

220
221
200

202
201

p r
Consider a program segment:
int *p=(int*)malloc(3*sizeof(int)); // int size is 4 bytes
float *q=(float*)malloc(sizeof(float)); // float size is 8 bytes
int *r=(int*)malloc(4*sizeof(int)); // int size is 4 bytes
free(q)

12
Limitations of Dynamic Array
heap Memory (Horizontal View)

236
212
213

220
221
200

202
201

p r
Consider a program segment:
int *p=(int*)malloc(3*sizeof(int)); // int size is 4 bytes
float *q=(float*)malloc(sizeof(float)); // float size is 8 bytes
int *r=(int*)malloc(4*sizeof(int)); // int size is 4 bytes
free(q)
int *s=(int*)malloc(3*sizeof(int)); // int size is 4 bytes
Although free memory is more than required 3 x 4 = 12 bytes, yet it cannot be
allocated as it is not contiguous. Returns a null pointer. 13
Solution: Linked List
heap Memory (Horizontal View)

236
212
213

220
221
200

202
201

Suppose we need to store a list of 4 integers: 7, 10, 5, 9.

Instead of asking memory manager for an integer array of 4 elements, these 4


integers can be stored one at a time in memory in different places.

14
Solution: Linked List
heap Memory (Horizontal View)

236
212
213

220
221
200

202
201

p
Suppose we need to store a list of 4 integers: 7, 10, 5, 9.

int *p=(int*)malloc(sizeof(int)); *p=7;

15
Solution: Linked List
heap Memory (Horizontal View)

7 10

236
212
213

222
200

202
201

p q
Suppose we need to store a list of 4 integers: 7, 10, 5, 9.

int *p=(int*)malloc(sizeof(int)); *p=7;


int *q=(int*)malloc(sizeof(int)); *q=10;

16
Solution: Linked Listheap Memory (Horizontal View)

7 10
5

236
212
213

222
200

202
201

p r q
Suppose we need to store a list of 4 integers: 7, 10, 5, 9.

int *p=(int*)malloc(sizeof(int)); *p=7;


int *q=(int*)malloc(sizeof(int)); *q=10;
int *r=(int*)malloc(sizeof(int)); *r=5;

17
Solution: Linked List
heap Memory (Horizontal View)

7 10
5

233
212
213

222
200

202
201

r
9 s
p
Suppose we need to store a list of 4 integers: 7, 10, 5, 9.
q
int *p=(int*)malloc(sizeof(int)); *p=7;
int *q=(int*)malloc(sizeof(int)); *q=10;
int *r=(int*)malloc(sizeof(int)); *r=5;
int *s=(int*)malloc(sizeof(int)); *s=9;
Non-contiguous allocation: Hence it is not possible to traverse the list directly as
done in array.
18
Solution: Linked List
heap Memory (Horizontal View)

7 10
5

233
212
213

222
200

202
201

r
9 s
p
To traverse the elements of the list, one should store
q the address of the next element in
the list with each element.

19
Solution: Linked List
heap Memory (Horizontal View)

10
7 222 5 233
213 213 -1

233
213

222
9
202

p
To traverse the elements of the list {7, 10, 5, 9}, one should store the address of the
next element (pointer to next element) in the list with each element.

It is sufficient to know the address of (pointer to) the first node (also called as head
node) to retrieve all the elements of the list.

The last node points to null (represented by -1 here).


20
What If continuous memory is not available?

21
head

22
insert 7

head

23
head

24
insert 9

head

25
head

26
Linked List
● A linked list is a linear collection of data elements (called nodes), where the linear order is
given by means of pointers.
● Each node is divided into 2 parts:
▪ 1st part contains the information of the element.
▪ 2nd part is called the link field or next pointer field which contains the address
of the next node in the list.

struct Node { class Node {


public:
int data; int data;
struct Node *next; Node *next;
}; 5 7 3 1
};

Lec Anika Ashraf, CSE Dept, MIST 27


Linked List
● A linked list is a linear collection of data elements (called nodes), where the linear order is
given by means of pointers.
● Each node is divided into 2 parts:
▪ 1st part contains the information of the element.
▪ 2nd part is called the link field or next pointer field which contains the address of
the next node in the list.

class Node { class SingleLinkedList {


public: public:
int data; Node *head;
Node *next; };
}; 5 7 3 1
SingleLinkedList

Lec Anika Ashraf, CSE Dept, MIST 28


Creating a Linked List

Struct in C: Class in C++:


struct newnode{ class newnode{
int data; public:
struct newnode *next; int data;
}; newnode *next;
};

struct newnode *temp = newnode *temp=new newnode;


(struct newnode*) malloc(sizeof(struct
newnode));
Lec Anika Ashraf, CSE Dept, MIST 29
Creating a Linked List

● Case 1: Linked list is empty


● Case 2: Linked list is not empty

Lec Anika Ashraf, CSE Dept, MIST 30


● Case 1: Linked list is empty

n=5
Head=NULL Node *newNode = new Node;
newNode->data = val;
newNode->next = nullptr;
8 NULL

if (head == nullptr)
{
head = newNode;
}

Lec Anika Ashraf, CSE Dept, MIST 31


● Case 1: Linked list is empty

n=5
Head Node *newNode = new Node;
newNode->data = val;
newNode->next = nullptr;
8 NULL

if (head == nullptr)
{
head = newNode;
}

Lec Anika Ashraf, CSE Dept, MIST 32


● Case 2: Linked list is not empty
Head
Node *newNode = new Node;
newNode->data = val;
newNode->next = nullptr; 8 NULL 5 NULL

else
{ temp
Node *temp = head; (temp->data=8
while (temp->next != nullptr) temp->next=NULL)
{
temp = temp->next;
}
temp->next = newNode;
}
Lec Anika Ashraf, CSE Dept, MIST 33
● Case 2: Linked list is not empty
Head
Node *newNode = new Node;
newNode->data = val;
newNode->next = nullptr; 8 NULL 5 NULL

else
{ temp
Node *temp = head; (temp->data=8
while (temp->next != nullptr) temp->next=NULL)
{
temp = temp->next;
}
temp->next = newNode;
}
Lec Anika Ashraf, CSE Dept, MIST 34
● Case 2: Linked list is not empty
Head
Node *newNode = new Node;
newNode->data = val;
newNode->next = nullptr; 8 5 NULL 3 NULL

else
{ temp
Node *temp = head; (temp->data=8
while (temp->next != nullptr) temp->next=address of next node)
{
temp = temp->next;
}
temp->next = newNode;
}
Lec Anika Ashraf, CSE Dept, MIST 35
● Case 2: Linked list is not empty
Head
Node *newNode = new Node;
newNode->data = val;
newNode->next = nullptr; 8 5 NULL 3 NULL

else
{ temp
Node *temp = head; (temp->data=5
while (temp->next != nullptr) temp->next=NULL)
{
temp = temp->next;
}
temp->next = newNode;
}
Lec Anika Ashraf, CSE Dept, MIST 36
● Case 2: Linked list is not empty
Head
Node *newNode = new Node;
newNode->data = val;
newNode->next = nullptr; 8 5 3 NULL

else
{ temp
Node *temp = head; (temp->data=5
while (temp->next != nullptr) temp->next=address of the
{ next node)
temp = temp->next;
}
temp->next = newNode;
}
Lec Anika Ashraf, CSE Dept, MIST 37
Head
● Case 2: Linked list is not empty

8 5 3 NULL 7 NULL

temp

else
{
Node *temp = head;
while (temp->next != nullptr)
{
temp = temp->next;
}
temp->next = newNode;
}

Lec Anika Ashraf, CSE Dept, MIST 38


Head
● Case 2: Linked list is not empty

8 5 3 NULL 7 NULL

temp

else
{
Node *temp = head;
while (temp->next != nullptr)
{
temp = temp->next;
}
temp->next = newNode;
}

Lec Anika Ashraf, CSE Dept, MIST 39


Head
● Case 2: Linked list is not empty

8 5 3 NULL 7 NULL

temp

else
{
Node *temp = head;
while (temp->next != nullptr)
{
temp = temp->next;
}
temp->next = newNode;
}

Lec Anika Ashraf, CSE Dept, MIST 40


Head
● Case 2: Linked list is not empty

8 5 3 7 1 NULL

temp else
{
void createList(int n) if (head == nullptr) Node *temp = head;
{ { while (temp->next != nullptr)
for (int i = 1; i <= n; i++) head = newNode; {
{ } temp = temp->next;
Node *newNode = new Node; }
int val; temp->next = newNode;
cout << "Node " << i << ": "; }
cin >> val; }
newNode->data = val; cout << endl;
newNode->next = nullptr; }
Lec Anika Ashraf, CSE Dept, MIST 41
Basic Operations

● Traverse: Go through the list starting from first and print.

● Insert: Add a new node in the first, last or interior of the list.

● Delete: Delete a node from the first, last or interior of the list.

● Search: Search a node containing particular value in the linked list.

Lec Anika Ashraf, CSE Dept, MIST 42


Traversal of a Linear Linked list
● We start from the head. Point a node ‘temp’ to head.
● Need to continue and advance ‘temp’ to next node till node->next is not null.
● Print the values of each node as we go.

Lec Anika Ashraf, CSE Dept, MIST 43


Printing or Traversing List
void printList()
{
if (head == nullptr)
{cout << "No list!!\n";}
else
{
cout << "List: ";
Node *temp = head;
while (temp != nullptr)
{
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;}
}

Lec Anika Ashraf, CSE Dept, MIST 44


Insertion to a Linear Linked list
● Add a new node at the first, last or interior of a linked list.

Lec Anika Ashraf, CSE Dept, MIST 45


Insert First
● To add a new node to the head of the linear linked list, we need to construct a new node that is
pointed by pointer newitem.
● Assume there is a global variable head which points to the first node in the list.
● The new node points to the first node in the list. The head is then set to point to the new node.

Lec Anika Ashraf, CSE Dept, MIST 46


Insert First (Cont.)
● Step 1. Create a new node that is pointed by pointer newItem.
● Step 2. Link the new node to the first node of the linked list.
● Step 3. Set the pointer head to the new node.
newItem head

NULL

newItem head

NULL

newItem

NULL

head
Lec Anika Ashraf, CSE Dept, MIST 47
Insert First (Cont.)

newItem head
void insertFirst(int val)
{ NULL
Node *newItem = new Node; newItem
newItem->data = val; head
newItem->next = head; NULL
head = newItem;
cout << "Successfully inserted!\n\n"; newItem
}
NULL
head

Lec Anika Ashraf, CSE Dept, MIST 48


Insert Last
● To add a new node to the tail of the linear linked list, we need to construct a new node and set
it's link field to “NULL".
● Assume the list is not empty, locate the last node and change it's link field to point to the new
node.

Lec Anika Ashraf, CSE Dept, MIST 49


Insert Last (Cont.)
● Step1. Create the new node.
● Step2. Set a temporary pointer temp to point to the last node.
● Step3. Set temp to point to the new node and new node as last node.

head newItem

NULL

head newItem
temp

NULL

head newItem
temp

NULL

Lec Anika Ashraf, CSE Dept, MIST 50


Insert Last (Cont.)
void insertLast(int val)
{
Node *newNode = new Node;
newNode->data = val; head
newNode->next = nullptr;
if (head == nullptr) NULL
{ head temp
head = newNode;
} NULL
else
{
Node *temp = head;
while (temp->next != nullptr)
newItem
{ head temp
temp = temp->next;
} NULL
temp->next = newNode;
}
cout << "Successfully inserted!<<endl;}
Lec Anika Ashraf, CSE Dept, MIST 51
Insertion After a Target Value or to a Specific Index Position
● To insert to a desired location/position or after a target value, we need to traverse to that
specific position first.
● Then, need to link the new node (node to be inserted) in such a way that the chain
remains unbroken. That is, link the new node to the previous and next one.

Lec Anika Ashraf, CSE Dept, MIST 52


Insertion After a Target Value or to a Specific Index Position

Head Temp Temp

NULL

newnode

53
Insert at any(to a specific index position)
void insertAt(int pos, int val)
{
if (pos == 1)
insertFirst(val);
else
{
Node *newNode = new Node; Head Temp Temp
newNode->data = val;
newnode->next=NULL;
Node *temp = head; NULL
for (int i = 2; i < pos; i++)
{
if (temp == nullptr)
{
cout << "Insertion not possible\n"; newnode
return;
}
temp = temp->next;
}
newNode->next = temp->next;
temp->next = newNode;
cout << "Successfully inserted!<<endl;}}

Lec Anika Ashraf, CSE Dept, MIST 54


Deletion from a Linear Linked list
● Deletion can be done
● At the first node of a linked list.
● At the end of a linked list.
● Within the linked list.

Lec Anika Ashraf, CSE Dept, MIST 55


Delete First
● To delete the first node of the linked list, we not only want to advance the pointer head to
the second node, but we also want to release the memory occupied by the abandoned node.

Lec Anika Ashraf, CSE Dept, MIST 56


Delete First (Cont.)
● Step1. Initialize the pointer cur point to the first node of the list.
● Step2. Move the pointer head to the second node of the list.
● Step3. Remove the node that is pointed by the pointer cur.

Step 1

Step 3

Step 2

Lec Anika Ashraf, CSE Dept, MIST 57


Delete First (Cont.)
void deleteFirst()
{
if (head == nullptr)
{
Step 1
cout << "No list is created!\n";
}
else{
Node *cur = head;
head
head =
= head->next;
head->next; Step 2
delete
delete cur;
cur;
cout
cout <<
<< "Successfully
"Successfully Deleted!
Deleted! “<<endl;
“<<endl;

}
} Step 3
Lec Anika Ashraf, CSE Dept, MIST 58
Delete Last

● Two ways to delete the last element

Lec Anika Ashraf, CSE Dept, MIST 59


Delete Last (1st Way)

● To delete the last node in a linked list, we use a local variable, cur, to point to the second last
node.

Lec Anika Ashraf, CSE Dept, MIST 60


Delete Last

● To delete the last node in a linked list, we use a local variable, cur, to point to the second last
node.

Node *temp = head;


while (temp->next->next != nullptr)
{
temp = temp->next;
}
delete temp->next;
temp->next = nullptr;
cout << "Successfully Deleted!\n\n";

Lec Anika Ashraf, CSE Dept, MIST 61


Delete Last (2nd Way)
● Step1. Initialize pointer cur to point to the first node of the list, while the pointer prev has a value of NULL.
● Step2. Traverse the entire list until the pointer cur points to the last node of the list.
● Step3. Set NULL to next field of the node pointed by the pointer prev.
● Step4. Remove the last node that is pointed by the pointer cur.

Step 3
Step1

Step2 Step 4

Lec Anika Ashraf, CSE Dept, MIST 62


Delete Last (Cont.)
void deletelast(){
if(head==NULL)
cout<<”list is empty”;
Node *cur = head;
Node *prev=NULL;
while (cur->next!= nullptr)
{
prev=cur;
cur = cur->next;
}
if(prev!=NULL)
delete cur->next;
prev->next=NULL;
cur->next = nullptr;
delete
coutcout <<cur;
"Successfully
<< "Successfully Deleted!\n\n";
cout << "Successfully Deleted!\n\n";
Deleted!\n\n";
}
}
Lec Anika Ashraf, CSE Dept, MIST 63
Delete from Matching Target Value

● To delete a node that contains a particular value x in a linked list or is in a particular position,
we use a local variable, cur, to point to this node, and another variable, prev, to hold the
previous node.

1. temp=cur->next // 20
1. prev->next=cur->next 2. cur->next=cur->next->next
2. delete cur 3. delete temp

Lec Anika Ashraf, CSE Dept, MIST 64


Delete Any (Cont.)
● Step1. Initialize pointer cur to point to the first node of the list, while the pointer prev has a value of
null.
● Step2. Traverse the entire list until the pointer cur points to the node that contains value of x, and prev
points to the previous node.
● ……..

Step 1

Step 2

Lec Anika Ashraf, CSE Dept, MIST 65


Delete Any (Cont.)

● …….
● Step3. Link the node pointed by pointer prev to the node after the cur’s node.
● Step4. Remove the node pointed by cur.

Step 3

Step 4

Lec Anika Ashraf, CSE Dept, MIST 66


Delete Any (Cont.)
void deleteAny( int x ){
if (head = = NULL) //list empty
return;
Node *cur = head;
Node *prev = NULL;
if(cur->val==x){
head=head->next;
delta cur;}
while (cur->value != x){
prev = cur;
cur=cur->next;
}
if (prev != NULL)
prev->next = cur->next;
free(cur);
}

Lec Anika Ashraf, CSE Dept, MIST 67


Circular Linked List
▪ In a circular linked list every element has a link to its next element and the last
element has a link to the first element.
▪ That means circular linked list is similar to the single linked list except that the
last node points to the first node in the list. There is no NULL at the end.
▪ A circular linked list can be a singly circular linked list or doubly circular linked
list.

Single Circular Linked List head last

Lec Anika Ashraf, CSE Dept, MIST 68


Single Link Lists Vs Arrays

Lec Anika Ashraf, CSE Dept, MIST 69


Single Link Lists & Arrays – A Tough Choice

Lec Anika Ashraf, CSE Dept, MIST 70


Single Link Lists Vs Arrays
● Time Complexity: The biggest improvement in linked list over arrays is in
insertion and deletion time. Both operations themselves can be done here in
O(1), although keep in mind that, you may need to look up (search) a value
before inserting or deleting. Time complexity of search and traversal is O(n).

● Searching: Then, can we speed up the searching process? Unfortunately, as


for searching, it’s also essential to state that there is no method of optimizing
search in linked lists. In the array, at least we could keep the array sorted. Also,
as we don’t have any idea how long the linked list is, there is no way of
accomplishing a binary search.

Lec Anika Ashraf, CSE Dept, MIST 71


Single Link Lists Vs Arrays
● Space Complexity: Linked lists carry two major chunks of data, namely, the value and
the pointer per node. This indicates that the amount of data stored grows linearly with the
number of nodes in the list. Thus, the space complexity of the linked list is linear, i.e. O(n).

● Application: Linked lists are used in a variety of cases, most prominently being the
building block for other complex data structures. They may be used to implement stacks,
queues, graphs and hash tables. They also have particular use cases in applications, such as:

● Next and Previous page in a web browser – We can access the previous and next “url”
searched in a web browser by pressing the “back” and “next” buttons as they are
connected as a linked list.
● Music Player – Songs in the music player are connected to the previous and next song.
You can listen to the songs either from the beginning or end of the list.

Lec Anika Ashraf, CSE Dept, MIST 72


Thank you!

Lec Anika Ashraf, CSE Dept, MIST 73

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