0% found this document useful (0 votes)
28 views

LEC 4,5 Linked List

The document discusses linked lists and their operations in C++, including introducing linked lists, comparing arrays and linked lists, defining linked list nodes, creating single linked lists, traversing linked lists to display their contents, and inserting nodes into linked lists at the front, end, or any position. Linked lists allow dynamic memory allocation and efficient insertion/deletion of nodes, while arrays have fixed size and require moving elements to insert in the middle.

Uploaded by

demro channel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

LEC 4,5 Linked List

The document discusses linked lists and their operations in C++, including introducing linked lists, comparing arrays and linked lists, defining linked list nodes, creating single linked lists, traversing linked lists to display their contents, and inserting nodes into linked lists at the front, end, or any position. Linked lists allow dynamic memory allocation and efficient insertion/deletion of nodes, while arrays have fixed size and require moving elements to insert in the middle.

Uploaded by

demro channel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Benha University

Benha Faculty of Engineering Electrical Engineering Department

Data Structures and Algorithms


with C ++ (E1324)
LEC_4,5 Linked list
Lecturer:
Dr. Eman Salem
Today’s Discussion…
 Introduction to linked list

 Array versus linked list

 Linked lists operations in C++

 Types of linked lists

 Single linked list

 Doubly linked list

 Circular linked list


 Stack and queue implementation using linked list
Introduction to Linked Lists
Linked List
• A linked list is a dynamic data structure which allows to store data and manage data
efficiently.Typically, a linked list, in its simplest form looks like the following:
• There is a pointer (called head) points the first element (also called node)
• Successive nodes are connected by pointers.
• Last element points to NULL.
• It can grow or shrink in size during execution of a program.. It can be made just as
long as required.It does not waste memory space, consume exactly what it needs

head A B C NULL
Array versus Linked Lists
But what if you int main()
• In arrays don’t know how {
many items you’ll int array[100];
• Arrays are static data structure have ahead of …
}
time?

• Arrays are suitable for Then you have to


reserve enough slots arrayName

▪ Inserting/deleting an element at the end. for the largest 0 10


possible case. 1 15
2 20
▪ Randomly accessing any element(easy access to any 22
And what if you
3

4 25
element a[i] in constant time ). need to insert 5 30
a new item in 6 35
▪ Searching the list for a particular value. the middle of an array? 7 40
8 45
We have to move every 9 50
item below the insertion
spot down by one!
• In Linked lists
• adjacency between any two elements are maintained by means of links or pointers

• It is essentially a dynamic data structure

• Linked lists are suitable for


▪ Inserting an element at any position.

▪ Deleting an element from any where.

▪ Applications where sequential access is required.

▪ In situations, where the number of elements cannot be predicted beforehand.


Linked Lists Aren’t Perfect!

First of all, they’re much more


complex than arrays!!!

Second, to access the kth item, I have to


traverse down k-1 times from the head
first! No instant access!!!

And to add an item at the end of the


list… I have to traverse through all N
existing nodes first!

▪no easy access to i-th element wrt the head of the list
Types of Lists: Single Linked List Implementation
Depending on the way in which the links are used to maintain
adjacency, several different types of linked lists are possible.

Single linked list (or simply linked list)


• A head pointer addresses the first element of the list.
• Each element points at a successor element.
• The last element has a link value NULL.

Head
Or NULL
A B C
list
Defining a Node of a Linked List
Each structure of the list is called a node, and consists of two fields:
• Item (or) data
• Address of the next item in the list (or) pointer to the next node in the list
How to define a node of a linked list?

node To allocate new nodes:


struct node
{ Data node *p = new node;
int data; /* Data */ or
node *next; /* pointer*/ next ptr p = new node;
} ;
To change/access a node p’s value:
typedef node *ptr; p->data = 10;
cout << p->data;
To make node p link to another node
To make node q a “terminal” node: that’s at address q:
q->next = nullptr; p->next = q;
Example 1: Illustration
The structure: To create the links between nodes:
Ptr head= n1;
struct node n1->next = n2 ;
{
char name[30];
n2->next = n3 ;
int age; n3->next = NULL ;
node *next;
};
• Now the list looks like:

Also assume the list with three


head
nodes n1, n2 and n3 for 3 students.
name
Ptr n1 = new node; age
Ptr n2 = new node; next NULL
Ptr n3 = new node; n1 n2 n3
• To start with, we have to create a node (the first node), and make
head point to it.

ptr n1= new node;


n1->data = data; //Links the data field with data
n1->next = NULL; //Links the address field to NULL
Ptr head = n1;

It creates a single node. For example, if the data entered is 100 then the list look like

head
100 NULL
Creating a single linked list
If we need n number of nodes in the linked list:
• Allocate n newNodes, one by one.
• Read in the data for the newNodes.
• Modify the links of the newNodes so that the chain is formed.
ptr n1=new node;
ptr n2= new node;
ptr n3= new node;
ptr head = n1;
n1-> data=100;
n1-> next=n2;
n2-> data=200;
n2-> next=n3;
n3-> data=50;
n3-> next=null;

It creates n number of nodes . For e.g. if the data entered is 100, 200, 50 then the list look like

head
100 200 50 NULL
Operations on single linked list

• Traversing a list
• Printing, etc.

• Insertion of a node into a list


• At front, end and anywhere, etc.

• Deletion of a node from a list


• At front, end and anywhere, etc.

Programs that lose nodes have a memory leak


Single Linked List: Traversing(show function)
Once the linked list has been constructed and head points to the first node of the list,

• Follow the pointers. Traversal: given a pointer


to the first node of the list,
• Display the contents of the nodes as they are traversed. step through the nodes
• Stop when the next pointer points to NULL. of the list

The function show()is given. This function to be called from main() function as:

void show(ptr head)


{
ptr temp = head;
while(temp!= null)
{
cout<< temp->data<<endl; //Prints the data of current node
temp= temp->next; //Advances the position of current node

}
}
Single Linked List: Insertion

Insertion steps:
• Create a new node
• Manage links to
• Insert at front
• Insert at end
• Insert at any position
Insertion at Front
Steps to insert node at the beginning of singly linked list Step 2: Link the newly created node with
the head node, i.e. the newNode will now
Step 1: Create a new node. point to head node.

Step 3: Make the new node as the head node, i.e. now head node will point to newNode.
Insertion at front Function

void add_first(ptr &list, int val)


{
ptr temp = new node;
temp -> data=val;
temp -> next =list;
list= temp;
}
Single Linked List: Insertion at End
Steps to insert node at the end of Singly linked list
Step 1: Create a new node and make sure that the address part of the new node points to
NULL. i.e. newNode->next=NULL

Step 2: Traverse to the last node of the linked list and connect the last node of the list with
the new node, i.e. last node will now point to new node. (lastNode->next =
newNode).
Insertion at End Function
/* Create a new node and insert at the end of the linked list. */

void add_last(ptr &head, int val)


{
ptr p= new node;
p-> data= val;
p-> next =null;
ptr temp=head;
while(temp-> next!= null) //Traverse to the last node
{
temp=temp->next;
}
temp->next=p;
}
Single Linked List: Insertion at any Position
Steps to insert node at any position of Singly Linked List
Step 1: Create a new node. Step 2: Traverse to the n-1th position of
the linked list and connect the new node
with the n+1th node.
(newNode->next = temp->next)
where temp is the n-1th node.

Step 3: Now at last connect the n-1th node


with the new node i.e. the n-1th node will now
point to new node. (temp->next = newNode)
where temp is the n-1th node.
Insertion at any Position Function

void add_anyposition(ptr &n1, int val)


{
ptr p = new node;
p-> data=val;
p-> next =n1->next;
n1->next= p;
}
Single Linked List: Deletion

Deletion steps
• Manage links to
• Delete at front
• Delete at end
• Delete at any position
Free Memory after Deletion
• Do not forget to delete() memory location dynamically allocated for a
node after deletion of that node.

• It is the programmer’s responsibility to free that memory block.

• Failure to do so may create a dangling pointer – a memory, that is not


used either by the programmer or by the system.

• The content of a free memory is not erased until it is overwritten.


Single Linked List: Deletion at Front
Steps to delete first node of Singly Linked List
Step 1: Copy the address of first node i.e. Step 3: Disconnect the connection of
head node to some temp variable say toDelete. first node to second node.

Step 2: Move the head to the second node


of the linked list (head = head->next). Step 4: Free the memory occupied by the first node.
Deletion at Front Function

/* Delete the first node of the linked list */

void delete_first(ptr &head)


{
ptr temp = head;
head = temp->next;
delete(temp);
}

typedef node *ptr;


Single linked list: Deletion at End
Steps to delete last node of a Singly Linked List Step 2: If the last node is the head node
then make the head node as NULL else
Step 1: Traverse to the last node of the linked list
disconnect the second last node with
keeping track of the second last node in some temp
the last node i.e. secondLastNode->next = NULL
Variable say secondLastNode.

Step 3: Free the memory occupied by the last node.


Deletion at End Function

void delete_last(ptr &head)


{
ptr p,n;
p=head;
while (p->next !=null)
{
n=p;
p=p->next;
}
n->next=null;
delete(p);

}
Single Linked List: Deletion at any Position
Steps to delete a node at any position of Singly Linked List
Step 1: Traverse to the nth node of the singly
linked list and also keep reference of n-1th node Step 2: Reconnect n-1th node with the n+1th node i.e.
in some temp variable say prevNode. prevNode->next = toDelete->next
(Where prevNode is n-1th node and toDelete node
is the nth node and toDelete->next is the n+1th node).

Step 3: Free the memory occupied by the nth node i.e. toDelete node.
Deletion at any Position
void delete_anynode(ptr &n)
{
ptr p = n->next;
n->next = p->next;
delete(p);
}
Single Linked List: Reversing
Reversing a List: Iterative Method Function
Steps to reverse a Singly Linked List using Iterative method

curr = head
Prev =null
void reverse(ptr &head)
Next = null {
ptr prev= null;
ptr curr= head;
ptr next= null;

while(curr != null)
{
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head= prev;
}
continue to
Types of Lists: Double Linked List
Double linked list
• Pointers exist between adjacent nodes in both directions.
• The list can be traversed either forward or backward.
• Usually two pointers are maintained to keep track of the list, head
and tail.

head tail

null A B C
null
Defining a Node of a Double Linked List
Each node of doubly linked list (DLL) consists of three fields:
• Item (or) Data
• Pointer of the next node in DLL
• Pointer of the previous node in DLL node
Data
prev next

How to define a node of a doubly linked list (DLL)?

struct Node
{
string value;
Node * next;
Node * prev;
};
Double Linked List
• Doubly linked list is a collection of nodes linked together in a sequential way.
• Doubly linked list is almost similar to singly linked list except it contains two
address or reference fields, where one of the address field contains reference of
the next node and other contains reference of the previous node.

• Doubly linked list is sometimes also referred as bi-directional linked list since it
allows traversal of nodes in both direction.
• Since doubly linked list allows the traversal of nodes in both direction, we can
keep track of both first and last nodes.
Doubly-linked Lists: What Changes?
Every time we insert a new node or delete an existing node, we
must update three sets of pointers:

1. The new node’s next and previous pointers.


2. The previous node’s next pointer.
3. The following node’s previous pointer.

And of course, we still have special cases if


we insert or delete nodes at the top or the
bottom of the list.
Double versus Single Linked List
Advantages over singly linked list
1) A DLL can be traversed in both forward and backward direction.
2) The delete operation in DLL is more efficient if pointer to the node to be deleted
is given.

Disadvantages over singly linked list


1) Every node of DLL Require extra space for an previous pointer.
2) All operations require an extra pointer previous to be maintained.

disadvantages of singly linked list

Wouldn’t it be
One of the downsides Given a pointer
nice if we could
with our simple to a node, I can
move both
linked list is that only find nodes
directions in a
we can only travel in below it!
linked list?
one direction… down!
Types of Lists: Circular Linked List
Circular linked list
•The pointer from the last element in the list points back to the
first element

Doubly circular linked list: Basic structure of singly circular linked list:
Circular Linked List
• A circular linked list is basically a linear linked list that may be single- or
double-linked.
• The only difference is that there is no any NULL value terminating the list.
• In fact in the list every node points to the next node and last node points to
the first node, thus forming a circle. Since it forms a circle with no end to
stop it is called as circular linked list.
• In circular linked list there can be no starting or ending node, whole node
can be traversed from any node.
• In order to traverse the circular linked list, only once we need to traverse
entire list until the starting node is not traversed again.
• A circular linked list can be implemented using both singly linked list and
doubly linked list.
Circular linked list:
Advantages of a Circular linked list
• Entire list can be traversed from any node.
• Circular lists are the required data structure when we want a list to be accessed
in a circle or loop.
• Despite of being singly circular linked list we can easily traverse to its previous
node, which is not possible in singly linked list.

Disadvantages of Circular linked list


• Circular list are complex as compared to singly linked lists.
• Reversing of circular list is a complex as compared to singly or doubly lists.
• If not traversed carefully, then we could end up in an infinite loop.
• Like singly and doubly lists circular linked lists also doesn’t supports direct
accessing of elements.
Stack Implementation using Linked List

PUSH
OPERATION POP
OPERATION

top
top
Basic Idea
• In the array implementation, we would:

• Declare an array of fixed size (which determines the maximum


size of the stack).

• Keep a variable which always points to the “top” of the stack.


• Contains the array index of the “top” element.

• In the linked list implementation, we would:

• Maintain the stack as a linked list.


• A pointer variable top points to the start of the list.
• The first element of the linked list is considered as the stack top.
Pushing an element into stack Popping an element from stack

void push(int val) void pop()


{ {
ptr p=new node; node *temp = top;
p->data=val; if(top!=NULL)
if(top=NULL){ {
p->next=NULL; top=top->next;
top=p;} delete temp;
else{ }
p->next=top; else{
top=p;} cout<<"stack is empty";
}
} }

LINKED LIST
Queue: Linked List Structure
• Basic idea:
• Create a linked list to which items would be added to one end
and deleted from the other end.
• Two pointers will be maintained:
• One pointing to the beginning of the list (point from where
elements will be deleted).
• Another pointing to the end of the list (point where new
elements will be inserted). Rear

Front DELETION INSERTION


ENQUEUE
front rear

DEQUEUE
front rear
Queue Operations using Linked List

void enqueue()
{ void dequeue()
{
int val;
cout<<"Insert the element in queue : ptr temp = frront;
"<<endl;
cin>>val; if (frront == NULL) {
cout<<"Underflow"<<endl;
return;
ptr newnode= new node; }
newnode->data=val; else
if (temp->next != NULL) {
newnode->next=NULL; temp = temp->next;
cout<<frront->data <<endl;
if ((frront == NULL) && (rear == NULL)) delete(frront);
{ frront = temp;
} else {
frront=rear=newnode;} cout<<frront->data<<endl;
else{ delete(frront);
frront = NULL;
rear = NULL;
rear->next=newnode; }
rear=newnode; }
}}
Applications of linked List

• Image viewer – Previous and next images are linked, hence can be accessed by next and previous
button

• Previous and next page in web browser – We can access previous and next url searched in web
browser by pressing back and next button since, they are linked as linked list.

• Music Player – Songs in music player are linked to previous and next song. you can play songs
either from starting or ending of the list.
Any question?

If you try to solve problems yourself, then you


will learn many things automatically.

Spend few minutes and then enjoy the study.

You might also like