0% found this document useful (0 votes)
24 views89 pages

CH 3 Queue and Linked List Part II

The document discusses lists and their implementation using arrays. It defines lists and their operations like insertion, deletion and traversal. It also explains the static implementation of lists using arrays and provides algorithms to perform basic list operations like insertion at different positions and deletion.

Uploaded by

lmxcosmos
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)
24 views89 pages

CH 3 Queue and Linked List Part II

The document discusses lists and their implementation using arrays. It defines lists and their operations like insertion, deletion and traversal. It also explains the static implementation of lists using arrays and provides algorithms to perform basic list operations like insertion at different positions and deletion.

Uploaded by

lmxcosmos
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/ 89

3.

Queue and Linked List


Data Structure and Algorithms

Dr. Udaya Raj Dhungana


Assist. Professor
Pokhara University, Nepal
Guest Faculty
Hochschule Darmstadt University of Applied Sciences, Germany
E-mail: udaya@pu.edu.np and udayas.epost@gmail.com

1
Overview
Unit 3: Queue and Linked List (10 hrs)
1. Queue
1.1.Definition and Queue Operations
1.2.Queue ADT and its Array Implementation
1.3.Circular Queue and its Array Implementation
1.4.Double Ended Queue and Priority Queue
2. Linked List
2.1.List- Definition and List Operations
2.2.List ADT and its Array Implementation
2.3.Linked List- Definition and its Operations
2.4.Singly Linked List- Basic Operations, Singly Linked List ADT and
Implementation of Singly Linked List
2.5.Doubly Linked List and Circular Linked List
2.6.Linked Implementation of Stack and Queue

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 2


List
• A list is a finite, ordered sequence of data items known as elements.
• “Ordered” means each element has a position in the list
• “Ordered” does not mean the elements are sorted
• A list is a linear data structure in which
• elements can be inserted into any position in the list
• removed from any position in the list.
• Any element can be accessed from any position in the list.
• Examples:
• A Shopping list • A list of payroll records
• A list of integers • A list of students
• A list of fruits • A list of lists

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 3


List
• A list differs from the stack and queue data structure:

• Since Insertions and deletions in a list can be made in any position

• Each list element must have some data type.

• In Array implementations:

• all elements of the list are usually assumed to have the same data
type

• In other implementation:

• there is no conceptual objection to lists whose elements have


differing data types.

• A list can have elements of different data types

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 4


List

• A list is said to be empty when it contains no elements.


• The number of elements currently stored is called the length of the
list.
• The beginning of the list is called the head.
• The end of the list is called the tail.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 5


The List ADT
• We can define the ADT for a list as a set of objects and a set of
operations on that object.
• We will use an interface to formally define the list ADT- List
• The List defines the member functions that any list
implementation inheriting from it must support, along with their
parameters and return types.
• This interface does not specify how operations are implemented.
• The two common implementations of List are
• Array-based List (Static Implementation) and
• Linked List (Dynamic Implementation)

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 6


The List ADT
class List {
int list[size];
int head, tail;
public:
void insert_begin(int Item);
void insert_end(int Item);
void insert_pos(int Item, int pos); //insert at position pos
int delete_begin();
int delete_end();
int delete_pos(int pos); //insert at position pos
int delete_end(int item);
int length();
};

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 7


Static Implementation of List
• Array can be used to implement a list.

• If list is implemented using array, it is called static list.

• Advantages of Array Implementation:

• Data can be randomly accessed using an index

• Fast access of items in O(1)

• Requires less memory to store the data

• Array implementation is suitable when the data need to be accessed


randomly

• Linked list implementation is suitable when data need to be


sequentially accessed

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 8


Basic Operations of List
• Insertion: Insert an item into the list
• Insert at the beginning
• Insert at the end
• Insert at given position
• Deletion: Delete an item from the list
• Delete from the beginning
• Delete from the end
• Delete from the given position
• Delete an given element
• Traversing a list: visit the elements of list
• Concatenation: combine two list into a single list
• Merging: merge the two sorted list into the third sorted list.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 9


Basic Operations of List
• Consider an array: int list[5];
• MaxSize = 5
• head = -1 tail = -1 (Initially) -> empty list

head tail

11 22 33 44

0 1 2 3 4

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 10


List: Insertion
• Insert an ITEM at the beginning: ITEM = 55
• Algorithm: head tail
FUNCTION INSERT-BEGINNING(item, head, tail)
IF tail == MaxSize - 1, then
PRINT “list is full” and
11 22 33 44
EXIT
i = tail 0 1 2 3 4
WHILE (i >= 0)
list[i + 1] = list[i]
head tail
i = i - 1
END WHILE
LIST[head] = ITEM
tail = tail + 1 55 11 22 33 44
END FUNCTION 0 1 2 3 4

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 11


List: Insertion
• Insert an ITEM at the end: ITEM = 55
• Algorithm: head tail

FUNCTION INSERT-END(item, tail)


IF tail == MaxSize - 1, then 11 22 33 44
PRINT “list is full” and 0 1 2 3 4
EXIT
tail = tail + 1 head tail
LIST[tail] = ITEM
END FUNCTION
11 22 33 44 55

0 1 2 3 4

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 12


List: Insertion
• Insert an ITEM at the given position: ITEM = 55. Position = 2
• Algorithm: head tail
FUNCTION INSERT-at-POSITION(item, Position)
IF tail == MaxSize - 1, then
PRINT “list is full” and 11 22 33 44
EXIT
i = tail 0 1 2 3 4
WHILE (i >= Position)
list[i + 1] = list[i]
head
i = i - 1
END WHILE tail
LIST[Position] = ITEM
tail = tail + 1 11 22 33 33 44
END FUNCTION
0 1 2 3 4

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 13


List: Deletion
• Delete an ITEM from the beginning:
• Algorithm:
head tail
RETURN-TYPE FUNCTION DELETE-BEGINNING()
IF head == - 1, then
PRINT “list is empty” and 11 22 33 44
EXIT
item = list[head] 0 1 2 3 4
i = head
WHILE (i <= tail)
list[i] = list[i + 1] head tail
i = i + 1 11
END WHILE
tail = tail - 1
22 33 44
RETURN item
END FUNCTION
0 1 2 3 4

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 14


List: Deletion
• Delete an ITEM from the end:
• Algorithm: head tail

RETURN-TYPE FUNCTION DELETE-END()


IF head == - 1 or tail = -1, then 11 22 33 44
PRINT “list is empty” and 0 1 2 3 4
EXIT
item = list[tail] head tail
tail = tail - 1 44
RETURN item
END FUNCTION 11 22 33

0 1 2 3 4

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 15


List: Deletion
• Delete an ITEM from the given position: Position = 2
• Algorithm:
head tail
RETURN-TYPE FUNCTION DELETE-at-POSITION(Position)
IF head == - 1 or tail = -1, then
PRINT “list is empty” and 11 22 33 44
EXIT
item = list[Position] 0 1 2 3 4
i = Position
WHILE (i <= tail)
list[i] = list[i + 1] head tail
i = i + 1 33
END WHILE
tail = tail - 1
11 22 44
RETURN item
END FUNCTION
0 1 2 3 4

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 16


List: Classwork

Write algorithms:
• To insert an item in sorted list
• To delete a given ITEM from the list

head tail

Item = 66
11 22 33 44

0 1 2 3 4

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 17


List: Classwork
Write algorithms:
• To concatenate two lists into a single third list

head tail

33 66 head tail

0 1 Concatenate
33 66 55 44 11
head tail
0 1 2 3 4

55 44 11

0 1 2
Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 18
List: Classwork
Write algorithms
• To merge two lists into a single third list

head tail

33 66 head tail

0 1 Merge
11 33 44 55 66
head tail
0 1 2 3 4

11 44 55

0 1 2
Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 19
Array and List
• In a list, the missing spot is filled in when something is deleted.
• In an array, an empty variable is left behind when something is
deleted.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 20


Linked List
• Linked list is the dynamic implementation of list
• Linked List addresses some of the limitations of Arrays
• It should be noted:
• For some applications, Arrays are the best data type to use.
• The decision to use an array or linked list depends on the nature
of application

Fig. a singly linked list

head A B C null

node 1 node 2 node 3

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 21


Linked List
• A linked list is a collection of objects linked together by references
from an object to another object.
• By convention these objects are named as nodes.
• So the basic linked list (commonly called singly linked list) consists
of nodes where each node contains
• one or more data fields and
• a reference to the next node
• The last node contains a null reference to indicate the end of the
list.
Fig. a singly linked list

head A B C null

node 1 node 2 node 3


Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 22
Linked List
• Unlike arrays where memory is allocated as a contiguous block of
memory, the memory required for each node can be allocated as
needed thereby providing a better way to manage free memory.
• The entry point into a linked list is always the head of the list.
• The head is NOT a separate node, but a reference to the first Node
in the list.

Fig. a singly linked list

head A B C null

node 1 node 2 node 3

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 23


Linked List
• If the list is empty then the head has the value null.
• Unlike Arrays, nodes cannot be accessed by an index. One must
begin from the head and traverse the list to access the Nodes in the
list.
• Insertions of new Nodes and deletion of existing nodes are fairly easy
to handle (once you find the node)

Fig. a singly linked list

head A B C null

node 1 node 2 node 3

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 24


Linked List
• The name of a node is itself a reference (pointer) to itself.
• There can be one or more data fields in a node
• The data field contains the actual data needed to be stored
• The link field points to the next node (it actually contains the
address of the next node to which it points to)

node2 Pointer to
Data field Link field next node

node2

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 25


Linked List
• Coding a node:

class node info link

{
node2
int info;
node *link; node2
};

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 26


Implementation of Linked List
• Linked list itself a dynamic implementation of list.

• However, we can use two array-lists to implement the linked list.

• In this sense, a linked list can be implemented in two ways:

• Static implementation (array-based implementation of linked list)

• Dynamic implementation

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 27


Array-based Implementation of Linked List
info link
• Two array lists are used to implement the linked
list 0
• One of them (say info list) is used to store the 1
actual data
A node
2
• Other (say link list) is used to point to the index
of the next element which is stored in info list. 3
• A pointer to next element is represented by an 4
array index info field link field
5
• The null pointer is represented by invalid index -1
6
• The corresponding memory cells of two arrays are
used to denote a node of linked list as shown in 7
figure: 8
9
10

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 28


Array-based Implementation of Linked List
info link
• Coding a node:
0
class node {
int info, link; 1
}; 2 22 8
• Creating an array of nodes: 3
node list[11]; 4
list = 5 11 2
• Accessing nodes:
6 55 -1
for(i = 5; i != -1; i = list[i].link){
7
cout<<list[i].info;
}; 8 33 10
9
list = 5 11 2 22 8 33 10 44 6 55 -1 10 44 6

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 29


Dynamic Implementation of Linked List

• To better understand linked list and its dynamic nature, let's use the analogy
of something we are all familiar with; contact list on our phone. Imagine will
have five names in our phone contact which are implemented using a static
data structure such as arrays like [Abby, Demi, Gina, Rita, Ursula]. In a
structure such this, if another name 'Bobby' is to be inserted between Abby
and Demi, it means the size of the structure has to be increased by one, and
the data items from Demi has to be shifted one position to the right. While
that may not seem like much work given the number of contacts in this case,
imagine a case of 10,000 or 1,000,000 contacts, shifting and repositioning
that much data would amount to enormous strain on the computer processing
resources. That is where dynamic data structures such as linked list come in.
Rather than representing data contiguously next to each other in the
computer memory, linked list employs the concept of nodes and pointers. A
node holds the data item in the particular memory block and a pointer links
from one node to another and references the memory address of the next and
previous nodes (in the case of doubly linked list). So, we can represent our
contacts list using a linked list as follows:

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 30


Dynamic Implementation of Linked List

• —>[Abby]-->[Demi]-->[Gina]-->[Rita]-->[Ursula]-->NULL
• [Abby] is known as the head (first) node and the arrows represent the
pointers. [Ursula] is known as the tail (last) node and it references to
NULL to indicate the end of the list. Notice the first arrow has no
previous node, it is known as the local pointer variable without which
we can not traverse the linked list.
• To add [Bobby] in between [Abby] and [Demi], all we need to do is to set
[Bobby]'s next pointer to reference [Demi] and [Abby]'s next pointer to
reference [Bobby]. As you can see, there is no need to re-adjust the
positions of the other elements in the structure. In the same way,
deleting a node such as [Gina] would require that we disconnect its next
pointer from [Rita] while the next pointer of [Demi] is then set to
reference [Rita]. Regardless of whether the number of nodes is just a
few or in the millions, the insertion and removal operations is the same
and proves to be more effective than in other data structure types.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 31


Dynamic Implementation of Linked List

• Like arrays, Linked List is a linear data structure.

• Unlike arrays, linked list elements are not stored at a contiguous


location; the elements are linked using pointers.

• A node in a linked list contains:

1. One or more data fields which stores the data in the list

2. A link pointer which points to the next node in the list

• To keep track of nodes in linked list, we must know the pointer to


the fist element (called head) of the linked list

• Note that the name of a node is itself a pointer to itself.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 32


Why Linked List?
• Arrays can be used to store linear data of similar types, but arrays have the following
limitations.

• The size of the arrays is fixed: So we must know the upper limit on the number of
elements in advance. Also, generally, the allocated memory is equal to the upper limit
irrespective of the usage.

• Inserting a new element in an array of elements is expensive because the room has to
be created for the new elements and to create room existing elements have to be
shifted. Deletion is also expensive with arrays due to same reason.

• Pointers in linked list overcome the above limitations at the cost of extra space for pointers.

• The list is not required to be contiguously present in the memory. The node can reside any
where in the memory and linked together to make a list. This achieves optimized utilization
of space.

• list size is limited to the memory size and doesn't need to be declared in advance.

• Empty node can not be present in the linked list.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 33


Basic Operations of Linked List

• Insert an element

• Delete an element

• Traversing an element

• Searching an element

1. Traversing a linked list.


2. Appending a new node (to the end) of the list
3. Prepending a new node (to the beginning) of the list
4. Inserting a new node to a specific position on the list
5. Deleting a node from the list
6. Updating the data of a linked list node

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 34


Types of Linked List

• Singly Linked List

• Doubly Linked List

• Circular Linked List

• Singly Circular Linked List

• Doubly Circular Linked List

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 35


Singly Linked List
• Singly linked list is a linked list in which every node has only one link pointer to
point to the next node only. Therefore, a node has:
• One or more data field(s) to store data and
• A single link field to point to the next node in the list (i.e. the link part of
the node stores the address of its immediate successor.)
• The last node contains null pointer to indicate end of the list
• It is also called one-way list because:
• Its nodes can be traversed in one direction only
(Traversal: Unidirectional from head node to tail node)

Fig. a singly linked list

head 11 22 33 null

node 1 node 2 node 3

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 36


Singly Linked List (in C++)
// Creating a node
class Node { // Assign value values
public: node1->value = 11;
int value; node2->value = 22;
Node* next; node3->value = 33;
}; head
// Connect nodes
node1->next = node2;
Fig. a singly linked
void main() {
Node* head; node2->next = node3;
11 node2 22 node3 33 null
Node* node1 = NULL; node3->next = NULL;
Node* node2 = NULL; node1 node2 node3
Node* node3 = NULL; // print the linked list value
head = node1;
// allocate 3 nodes in the heap while (head != NULL) {
node1 = new Node(); cout << head->value;
node2 = new Node(); head = head->next;
node3 = new Node(); }
}

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 37


Singly Linked List (in C)
#include <stdio.h>
// Allocate memory
#include <stdlib.h>
node1 = malloc(sizeof(struct node));
// Creating a node
node2 = malloc(sizeof(struct node));
struct node {
node3 = malloc(sizeof(struct node));
int value;
struct node *next;
// Assign value values head
};
node1->value = 11;
// print the linked list value
node2->value = 22;
Fig. a singly linked
void printLinkedlist(struct node *p) {
node3->value = 33;
while (p != NULL) { 11 node2 22 node3 33 null
printf("%d ", p->value);
// Connect nodes
p = p->next; node1 node2 node3
node1->next = node2;
}
node2->next = node3;
}
node3->next = NULL;
void main() {
// Initialize nodes
// printing node-value
struct node *head;
head = node1;
struct node *node1 = NULL;
printLinkedlist(head);
struct node *node2 = NULL;
}
struct node *node3 = NULL;

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 38


Singly Linked List Inserting a node at the beginning

Algorithm:
1.Create a newNode
2.Assign value to newNode
3.Check whether list is Empty (head == NULL)
4.If it is Empty then,
set newNode→next = NULL and
head = newNode.
5.If it is Not Empty then,
set newNode→next = head and
head = newNode.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 39


Inserting a node at the beginning
head = node1
head
Singly Linked List

11 node2 22 node3 33 null

node1 node2 node3

head

11 node2 22 node3 33 null


e
Nod

ad node1 node2 node3


new

he
=
d=

e
od
hea

wN
ne

44 node1

newNode head 44 node1 11 node2 22 node3 33 null

newNode node1 node2 node3

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 40


Singly Linked List Inserting a node at the end

Algorithm:
1.Create a newNode
2.Assign value to newNode
3.Set newNode → next as NULL.
4.Check whether list is Empty (head == NULL).
5.If it is Empty then, set head = newNode.
6.If it is Not Empty then,
a.de ne a node pointer temp and ini alize
with head.
7.Keep moving the temp to its next node un l it
reaches to the last node in the list (un l temp →
next is equal to NULL).
8.Set temp → next = newNode.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 41


fi
ti
ti
ti
Inserting a node at the end
head = node1
head
Singly Linked List

11 node2 22 node3 33 null

node1 node2 node3

head
11 node2 22 node3 33 newNode

node1 node2 node3

44 null
newNode

head 11 node1 22 node2 33 node3 44 null

node1 Node2 Node3 newNode

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 42


Inserting a node after a given node
Algorithm:
Singly Linked List

1. Create a newNode and assign a value.


2. Check whether list is Empty (head == NULL)
3. If it is Empty then, set newNode → next = NULL and head = newNode.
4. If it is Not Empty then, define a node pointer temp and initialize
with head.
5. Keep moving the temp to its next node until it reaches to the node
after which we want to insert the newNode (until temp1 → data is
equal to location, here location is the node value after which we
want to insert the newNode).
6. Every time check whether temp is reached to last node or not. If it
is reached to last node then display 'Given node is not found in the list
and Insertion is not possible!!!' and terminate the function. Otherwise
move the temp to next node.
7. Finally, Set 'newNode → next = temp → next' and 'temp →
next = newNode'

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 43


Deleting a node from the beginning
Algorithm:
Singly Linked List

1. Check whether list is Empty (head == NULL)


2. If it is Empty then,
a. display 'List is Empty. Deletion is not possible' and
b. terminate the function.
3. If it is Not Empty then,
a. define a Node pointer 'temp' and initialize with head.
4. Check whether list is having only one node (temp → next == NULL)
a. If it is TRUE then
i. set head = NULL and delete temp (Setting Empty list conditions)
b. If it is FALSE then
i. set head = temp → next, and
ii. delete temp.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 44


Deleting a node from the end
Algorithm:
Singly Linked List

1. Check whether list is Empty (head == NULL)


2. If it is Empty then, display 'List is Empty. Deletion is not possible' and
terminate the function.
3. If it is Not Empty then,
a. define two Node pointers 'temp1' and 'temp2' and
b. initialize 'temp1' with head.
4. Check whether list has only one Node (temp1 → next == NULL)
a. If it is TRUE. Then,
i. set head = NULL and delete temp1. And terminate the
function.
b. If it is FALSE. Then,
i. set 'temp2 = temp1 ' and
ii. move temp1 to its next node. Repeat the same until it reaches
to the last node in the list. (until temp1 → next == NULL) every
time set 'temp2 = temp1' before moving the 'temp1' to its next
node.
5. Finally, Set temp2 → next = NULL and delete temp1.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 45


Deleting a specific node
Algorithm:
Singly Linked List

1. Check whether list is Empty (head == NULL)


2. If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate the function.
3. If it is Not Empty, define two Node pointers 'temp1' and 'temp2' and initialize 'temp1' with head.
4. Keep moving the temp1 until it reaches to the exact node to be deleted or to the last node. And
every time set 'temp2 = temp1' before moving the 'temp1' to its next node.
5. If it is reached to the last node then display 'Given node not found in the list! Deletion not
possible!!!'. And terminate the function.
6. If it is reached to the exact node which we want to delete, then check whether list is having
only one node or not
7. If list has only one node and that is the node to be deleted, then set head = NULL and
delete temp1 (free(temp1)).
8. If list contains multiple nodes, then check whether temp1 is the first node (temp1 == head).
9. If temp1 is the first node then move the head to the next node (head = head → next) and
delete temp1.
10. If temp1 is not first node then check whether it is last node in the list (temp1 → next == NULL).
11. If temp1 is last node then set temp2 → next = NULL and delete temp1 (free(temp1)).
12. If temp1 is not first node and not last node then set temp2 → next = temp1 → next and
delete temp1 (free(temp1)).
Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 46
Singly Linked List Deleting a specific node

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 47


Traversing and displaying the nodes

Displaying the contents of a linked list is very simple. We keep moving the temp
Singly Linked List

node to the next one and display its contents.


When temp is NULL, we know that we have reached the end of the linked list so
we get out of the while loop.

Algorithm:
//C implementation
1. Check whether list is Empty (head == NULL) struct node *temp = head;
2. If it is Empty then, display 'List is Empty.' and printf("\n\nList elements are - \n");
terminate the function.
while(temp != NULL) {
3. If it is Not Empty then, define a Node
printf("%d --->",temp->data);
pointer 'temp' and initialize with head.
temp = temp->next;
4. Keep displaying temp → data with an arrow (--->)
until temp reaches to the last node }

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 48


Doubly Linked List

• A doubly linked list is a list that has two references from each node,
• one to the next node and
• another to the previous node.
• Doubly linked lists also starts from head node, but provide access both ways.
• The flexibility of a doubly linked list is that one can traverse forward or
backward from any node.
• A doubly linked list may be suitable for applications that require frequent
updates to nodes that are in a close range.
TAIL

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 49


Doubly Linked List
• The singly linked list allows for direct access from a list node only to the next
node in the list.

• A doubly linked list allows convenient access from a list node to the next node
and also to the preceding node on the list.

• The doubly linked list node accomplishes this in the obvious way by storing two
pointers:

• one to the node following it (as in the singly linked list), and

• a second pointer to the node preceding it. TAIL

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 50


Doubly Linked List

• Doubly linked list is thus a sequence of elements in which every


element has links to its previous element and next element in the
sequence.

• A node is represented as

class node
{ node node1;
int data;
node *next;
node *prev;
}
node1

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 51


Doubly Linked List

• A three-node doubly linked list (in C) can be created as:


/* Initialize nodes */ /* Connect nodes */
struct node *head; node1->next = node2;
struct node *node1 = NULL; node1->prev = NULL;
struct node *node2 = NULL; node2->next = node3;
struct node *node3 = NULL; node2->prev = node1;
node3->next = NULL;
/* Allocate memory */ node3->prev = node2;
node1 = malloc(sizeof(struct node));
node2 = malloc(sizeof(struct node)); /* Save address of first node in head */
node3 = malloc(sizeof(struct node)); head = node1;
head
/* Assign data values */
node1->data = 11; null 11 node2 node1 22 node3 node2 33 null
node2->data = 22;
node3->data = 33; node1 node2 node3

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 52


Operations on Doubly Linked List

1. Insertion
Doubly Linked List

• Inserting at Beginning of the list


• Inserting at End of the list
• Inserting at Specific location in the list
2. Deletion
• Deleting from Beginning of the list
• Deleting from End of the list
• Deleting a Specific Node
3. Traversal

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 53


Inserting a node at beginning
Algorithm:
Doubly Linked List

Node *newNode;
1.Create a newNode newNode = new Node();
2.Assign value to newNode newNode->data = 33;
3.Assign newNode → previous = NULL newNode->prev = null;
if(head == null){
4.Check whether list is Empty (head == NULL)
newNode->next = null;
5.If it is Empty then,
head = newNode;
set newNode→next = NULL and }
head = newNode. else {
6.If it is Not Empty then, newNode->next = head;
set newNode→next = head and head = newNode;
head = newNode. }

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 54


Doubly Linked List Inserting a node at beginning

head

null 11 node2 node1 22 null


null 33 node1
node1 node2
newNode

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 55


Inserting a node at the end

Algorithm: Node *newNode;


Doubly Linked List

1.Create a newNode and assign value to newNode newNode = new Node();


newNode->data = 44;
2.Set newNode → next as NULL.
newNode->next = null;
3.Check whether list is Empty (head == NULL).
4.If it is Empty then, set if(head == null){
• head = newNode and head = newNode;
• newNode → previous = NULL newNode->prev = null;

5.If it is Not Empty then,


}
else {
a.de ne a node pointer temp and ini alize
Node *temp = head;
with head.
while(temp->next != null){
6.Keep moving the temp to its next node un l it temp = temp->next;
reaches to the last node in the list (un l temp → }
next is equal to NULL). temp->next = newNode;
7.Set temp → next = newNode and newNode → newNode->previous = temp;
previous = temp }

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 56


fi
ti
ti
ti
Inserting at specific location (after a node)
Algorithm:
Doubly Linked List

1. Create a newNode and assign a value.


2. Check whether list is Empty (head == NULL)
3. If it is Empty then, set newNode → previous = NULL, newNode →
next = NULL and head = newNode.
4. If it is Not Empty then, define two node pointers temp1 and temp2
and initialize temp1 = head.
5. Keep moving the temp1 to its next node until it reaches to the node
after which we want to insert the newNode (until temp1 → data is
equal to location, here location is the node value after which we
want to insert the newNode).
6. Every time check whether temp1 is reached to last node or not. If it
is reached to last node, then display 'Given node is not found in the
list and Insertion is not possible!!!' and terminate the function.
Otherwise move the temp1 to next node.
7. Finally, Set temp2 = temp1 → next, temp1 → next = newNode,
newNode → previous = temp1, newNode → next = temp2 and temp2 →
previous = newNode

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 57


Delete a node from beginning
Algorithm:
Doubly Linked List

1. Check whether list is Empty (head == NULL)


2. If it is Empty then,
a. display 'List is Empty. Deletion is not possible' and
b. terminate the function.
3. If it is Not Empty then,
a. define a Node pointer 'temp' and initialize with head.
4. Check whether list is having only one node (temp → next == NULL)
a. If it is TRUE then
i. set head = NULL and delete temp (Setting Empty list conditions)
b. If it is FALSE then
i. set head = temp → next, and head → previous = NULL
ii. delete temp.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 58


Delete a node from the end
Algorithm:
Doubly Linked List

1. Check whether list is Empty (head == NULL)


2. If it is Empty then,
a. display 'List is Empty. Deletion is not possible' and
b. terminate the function.
3. If it is Not Empty then,
a. define a Node pointer 'temp' and
b. initialize temp = head.
4. Check whether list has only one Node (temp → next and temp →
previous are NULL)
a. If it is TRUE. Then,
i. set head = NULL and
ii. delete temp.
iii. terminate the function.
b. If it is FALSE. Then,
i. move temp to its next node until it reaches to the last node in
the list. (until temp → next == NULL)
5. Finally, Set temp →previous → next = NULL and delete temp.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 59


Delete a specific node
Algorithm:
Doubly Linked List

1. Check whether list is Empty (head == NULL)


2. If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate the function.
3. If it is Not Empty, define a Node pointer 'temp' and initialize temp = head.
4. Keep moving the temp until it reaches to the exact node to be deleted or to the last node.
5. If it is reached to the last node then display 'Given node not found in the list! Deletion not
possible!!!'. Terminate the function.
6. If it is reached to the exact node which we want to delete, then check whether list is having
only one node or not
7. If list has only one node and that is the node to be deleted, then set head = NULL and
delete temp.
8. If list contains multiple nodes, then check whether temp is the first node (temp == head).
9. If temp is the first node then move the head to the next node (head = head → next) and
delete temp.
10. If temp is not first node then check whether it is last node in the list (temp → next == NULL).
11. If temp is last node then set temp → previous → next = NULL and delete temp.
12. If temp is not first node and not last node then set temp → previous → next = temp → next, temp
→ next → previous = temp → previous and delete temp.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 60


Traversing

• Traversal is a technique of visiting each node in the linked list.


Doubly Linked List

• In a doubly linked list, we have two types of traversals as we have two pointers with
different directions in the doubly linked list.

1. Forward traversal –

a. Traversal is done using the next pointer which is in the forward direction.

b. Start with the front node and visit all the nodes until the node becomes
NULL.

2. Backward traversal –

a. Traversal is done using the previous pointer which is the backward


direction.

b. Start with the end node and visit all the nodes until the node becomes
NULL.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 61


Doubly Linked List Traversing

Forward Traversing Backward Traversing

void forward_traverse() void backward_traverse()


{ {
node *trav; node *trav;
trav = front; trav = tail;
while(trav != NULL) while(trav != NULL)
{ {
cout<<trav->data<<endl; cout<<trav->data<<endl;
trav = trav->next; trav = trav->prev;
} }
} }

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 62


Circular singly linked list
• A circular linked list is a sequence of elements in which every
element has a link to its next element in the sequence and the last
element has a link to the first element.
• In single linked list, every node points to its next node in the
sequence and the last node points NULL.
• But in circular linked list, every node points to its next node in the
sequence but the last node points to the first node in the list.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 63


Circular singly linked list
• In a circular singly linked list, the last node of the list contains a
pointer to the first node of the list.
• Circular linked list is similar to the single linked list except that the
last node points to the first node in the list.
• We traverse a circular singly linked list until we reach the same node
where we started.
• The circular singly liked list has no beginning and no ending. There is
no null value present in the next part of any of the nodes.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 64


Circular singly linked list: Operations
1. Insertion
• Inserting at Beginning of the list
• Inserting at End of the list
• Inserting at Specific location in the list
2. Deletion
• Deleting from Beginning of the list
• Deleting from End of the list
• Deleting a Specific Node
3. Traversal

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 65


Circular singly linked list: Implementation

Assignment

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 66


Circular doubly linked list
• A circular doubly linked list or a circular two-way linked list is a more complex type of linked
list which contains a pointer to the next as well as the previous node in the sequence.
• The circular doubly linked list does not contain NULL in the previous field of the first node
and the next field of the last node.
• Rather, the next field of the last node stores the address of the first node of the list, i.e.,
Head.
• Similarly, the previous field of the first field stores the address of the last node.
• A circular doubly linked list is one which has both the successor pointer and predecessor
pointer in circular manner.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 67


Circular doubly linked list
• The advantage is that we can traverse back and forth using the next
and previous pointers.
• As the last element is linked with the head so we can easily jump
from the tail to the head of the Data structure.
• The disadvantage is that it needs two pointers for each node which
makes it occupy extra space.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 68


Circular doubly linked list: Operations
1. Insertion
• Inserting at Beginning of the list
• Inserting at End of the list
• Inserting at Specific location in the list
2. Deletion
• Deleting from Beginning of the list
• Deleting from End of the list
• Deleting a Specific Node
3. Traversal

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 69


Circular doubly linked list: Implementation

Assignment

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 70


Circular linked list: Applications
• The real life application where the circular linked list is used is our
Personal Computers, where multiple applications are running. All the
running applications are kept in a circular linked list and the OS gives
a fixed time slot to all for running. The Operating System keeps on
iterating over the linked list until all the applications are completed.
• Another example can be Multiplayer games. All the Players are kept
in a Circular Linked List and the pointer keeps on moving forward ass
a player's chance ends.
• Circular Linked List can also be used to create Circular Queue. In a
Queue we have to keep two pointers, FRONT and REAR in memory all
the time, where as in Circular Linked List, only one pointer is
required.
• Browser surfing where a record of pages visited in the past by the
user, is maintained in the form of circular linked lists and can be
accessed again on clicking the previous button.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 71


Advantages of Linked List over Arrays

• Dynamic size: the size in linked list can grow or shrink in run time

• There is no waste of memory space in linked list

• Fast and efficient insertion and deletion (since it does not require
shifting operations)

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 72


Disadvantages of Linked List over Arrays

•Random access is not allowed (Slow access of data).


•We have to access elements sequentially starting from the first
node. So we cannot do binary search with linked lists efficiently
with its default implementation.
•Extra memory space for a pointer is required with each element of
the list.
•Not cache friendly.
•Since array elements are contiguous locations, there is locality
of reference which is not there in case of linked lists.
•Linked list are more complex to code than arrays

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 73


Linked Implementation of Stack
• The major problem with the stack implemented using an array is, it
works only for a fixed number of data values. That means the amount of
data must be specified at the beginning of the implementation itself.
• Stack implemented using an array is not suitable, when we don't know
the size of data which we are going to use.
• A stack data structure can be implemented by using a linked list data
structure.
• The stack implemented using linked list can work for an unlimited
number of values. That means, stack implemented using linked list
works for the variable size of data.
• So, there is no need to fix the size at the beginning of the
implementation.
• The Stack implemented using linked list can organize as many data
values as we want.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 74


Linked Implementation of Stack
• In linked list implementation of a stack, every
new element is inserted as 'top' element. That
means every newly inserted element is pointed
by 'top'.
• Whenever we want to remove an element from
the stack, simply remove the node which is
pointed by 'top' by moving 'top' to its previous
node in the list.
• The next field of the first element must be
always NULL.
• In the above example, the last inserted node is
99 and the first inserted node is 25. The order
of elements inserted is 25, 32,50 and 99.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 75


Linked Implementation of Stack
Push operation:

1. Create a newNode with given value.


2.Check whether stack
is Empty (top == NULL)
3. If it is Empty, then set newNode →
next = NULL.
4. If it is Not Empty, then set newNode →
next = top.
5. Finally, set top = newNode.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 76


Linked Implementation of Stack
Pop Operation:

1. Check whether stack is Empty (top ==


NULL).
2. If it is Empty, then display "Stack is
Empty" and terminate the function
3. If it is Not Empty, then define
a Node pointer 'temp' and set it to 'top'.
4. Then set 'top = top → next'.
5. Finally, delete 'temp'.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 77


Linked Implementation of Stack using C++

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 78


Linked Implementation of Queue
• The major problem with the queue implemented using an array is, it
will work for an only fixed number of data values.
• Queue using an array is not suitable when we don't know the size of
data which we are going to use.
• A queue data structure can be implemented using a linked list data
structure.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 79


Linked Implementation of Queue
• The queue which is implemented using a linked list can work for an
unlimited number of values. (No need to fix the size at the beginning
of the implementation).
• The Queue implemented using linked list can organize as many data
values as we want.
• In linked list implementation of a queue, the last inserted node is
always pointed by 'rear' and the first node is always pointed by 'front'.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 80


Linked Implementation of Queue
Enqueue operation:
1. Create a newNode with given value and set 'newNode → next' to NULL.
2. Check whether queue is Empty (rear == NULL)
3. If it is Empty then, set front = newNode and rear = newNode.
4. If it is Not Empty then,
set rear → next = newNode and rear = newNode.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 81


Linked Implementation of Queue
Dequeue operation:
1. Check whether queue is Empty (front == NULL).
2. If it is Empty, then
display "Queue is Empty" and stop
3. If it is Not Empty then,
define a Node pointer 'temp' and set temp = front.
set 'front = front → next' and
delete 'temp'.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 82


Linked Implementation of Queue using C++

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 83


Applications of Linked List

• Implementation of stacks and queues


• Implementation of graphs (Adjacency list representation of graphs)
• Implementation of hash tables and heaps
• Dynamic memory allocation
• Maintaining directory of names
• Manipulation of polynomials by storing constants in the node of
linked list
• representing sparse matrices
• Image viewer / music player
• Previous and next page in web browser
• Used in Undo/redo functionality of editors

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 84


Sparse Matrix and Linked List

• A matrix which contains more number of ZERO values


than NON-ZERO values, is known as sparse matrix.
• To represent the sparse matrix using linked list, nodes
are created- each having four fields.
• Row: Index of row, where non-zero element is located
• Column: Index of column, where non-zero element is
located
• Value: Value of the non zero element located at index
– (row, column)
• Next node: Address of the next node

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 85


Sparse Matrix and Linked List

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 86


Polynomial and Linked List

• Polynomials and Sparse Matrix are two important applications of


arrays and linked lists.
• Each term in the polynomial expression (ax + bx + …. + jx+ k)
n n-1

consists of two parts:


• The coefficient and
• The exponent
• Each node requires third field which contains the address of the
term’s node which points to the next term of the polynomial.

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 87


Polynomial and Linked List

• A polynomial 4x + 6x + 10x + 6 is represented using linked list as:


3 2

Dr. Udaya R. Dhungana, Pokhara University, Nepal. udaya@pu.edu.np 88


THANK YOU

89

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