Lecture 5 Linked Lists in C++

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 40

Linked Lists in C++

What is a Linked List?


• A linked list is a linear data structure, in which the elements are NOT stored at
contiguous memory locations like arrays . Instead each element in a linked list
is stored in the form of a node.

• The elements in a linked list are linked using pointers as shown in the image
below:

• In simple words, a linked list consists of nodes where each node contains a data
field and a pointer(link) to the next node in the list.
• A node is a collection of two sub-
What is a Linked List?(2)
elements or parts. A data part
that stores the element and
a pointer(link) part, that points
to the next node.

• Usually the pointer is called next


or link 
• NB: Each node is created
dynamically i.e. ONLY as when
required, the node is created
and memory is allocated to it
What is a Linked List?(3)

• A linked list is formed when many such nodes are linked together to
form a chain. Each node points to the next node present in the order.
The first node is always used as a reference to traverse the list and is
called HEAD. The last node always points to NULL.
What is a Linked List?(4)
• Linked lists are one of the most important data structures ,in fact they are the
second most used data structure after arrays but unlike arrays they can store an
indefinite amount of items.

• We often face situations, where the data is dynamic in nature and number of
data can’t be predicted or the number of data keeps changing during program
execution. Linked lists are very useful in this type of situations

• Linked lists are a way to store data with structures so that the programmer can
automatically create a new place to store data whenever necessary. Specifically,
the programmer writes a struct or class definition that contains variables holding
information about something, and then has a pointer to a struct of its type. Each
of these individual struct or classes in the list are commonly known as a node.
Key Differences Between
Array and Linked List
1. An array is the data structure that contains a collection of
similar type data elements whereas the Linked list is considered as
non-primitive data structure contains a collection of unordered
linked elements known as nodes.

2. In the array the elements belong to indexes, i.e., if you want to


get into the fourth element you have to write the variable name
with its index or location within the square bracket. In a linked list
though, you have to start from the head and work your way
through until you get to the fourth element.
Key Differences Between
Array and Linked List (2)

3. Arrays are of fixed size. In contrast, Linked lists are dynamic


and flexible and can expand and contract its size.

4. Accessing an element in an array is fast thanks to indexing


while Linked list takes linear time, so it is quite a bit slower.

5. Operations like insertion and deletion in arrays consume a


lot of time. On the other hand, the performance of these
operations in Linked lists is fast.
Key Differences Between
Array and Linked List (3)
6. In an array, memory is assigned during compile time while in a Linked
list it is allocated during execution or runtime.

7. Elements are stored consecutively in arrays whereas it is stored


randomly in Linked lists.

8. In an array, the memory requirements are less due to actual data


being stored within the index in the array. In Linked lists however, there
is a need for more memory due to storage of additional next and
previous referencing elements.
So Why Linked List?
• Arrays can be used to store linear data of similar types, but arrays
have the following limitations.

(1) 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.

(2) 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.
Arrays Vs Linked Lists Summary
Singly Linked Lists (SLL)
• Each node has only ONE link part
and each link part contains the
address of the next node in the
list

• The Link part of the last node


contains NULL value which
signifies the end of the node
• myList is the header pointer
• Each node contains a value(data) which points at the first node in
part and a pointer to the next the list
node in the list
Basic Operations on a Linked List
1. Creating a List
2. Inserting an element in a list
3. Deleting an element from a list
4. Searching a list
5. Reversing a list
• The above definition is used to create every
node in the list. It defines the structure of every
Creating a Node node which will be in our linked list
• In C++, a linked list can be • The data field stores the element and the next is
implemented using a a pointer to store the address of the next node.
structure and pointers  • Noticed something unusual with next? In place
of a data type, struct node is written before
next. This is because its a self-referencing
struct node{ pointer. It means a pointer that points to
whatever it is a part of. Here next is a part of a
int data; node and it will point to the next node.
struct node* next; • NB: start is a pointer variable (also called the
Head) and will ALWAYS points to(or stores
}*start; address of) the first element of the linked list. It
start=NULL ; is initialized to NULL at beginning meaning the
list is empty sofar. Also note it’s a global
variable
node* create( int num) //suppose num=1 is passed from main i.e. the user
{
node* ptr; //declares ptr as pointer of datatype struct node
ptr = new node; //The new operator is used to create a new node and allocates memory to create
the new node dynamically.. This line thus creates a new node and returns the
address of the new node to the pointer ptr
if(ptr==NULL)
‘OVERFLOW’ // no memory available
exit(1);
else{
ptr->data=num; //stores num on the data part of the newly created node
ptr->next=NULL; //set next(i.e. the link part of the newly created node) to NULL
return ptr; //return the newly created node
}
} //The above code will create a new node with data as num i.e.(1) and next pointing to NULL.
To be called from main( ) as:-
void main( ){

node* ptr;
int data;
cout<<"Enter value to create new node: "; //prompts user to enter a value
cin>>data; //accepts input from the user

ptr=create(data); //passes input from user to function called create on r previous slide to
create a node
}
Basic Operations on a Linked List
1. Creating a List
2. Inserting an element in a list
3. Deleting an element from a list
4. Searching a list
5. Reversing a list
Inserting the node in a SLL
• There are 3 cases here:-

• Insertion at the beginning


• Insertion at the end
• Insertion after a particular node
• There are two steps to be followed:-
Insertion at the beginning
• (a) Make the next pointer of the new-
node point towards the first node of
the list
//p->next=temp;

• (b) Make the start pointer


(head)point towards this new
node //start=p;

• If the list is empty simply make the


start pointer point towards the new
node;
void insert_beg(node* p) //defines a function that takes pointer p as an argument. p points( or
stores the address), of the new node to be inserted (2)
{
node* temp; //declares temp as a pointer variable, pointing to the current first node(3)
represented by the dotted line from head and the 1 st node on the diagram before
if(start==NULL) //if the list is empty
{
start=p; //assign p to start (i.e. insert the new node at the beginning of the list)
cout<<“\n Node inserted successfully at the beginning”;
}
else { //if the list is NOT empty

temp=start; //Remember start stored the address of the previous first node(3), thus assign that
address to a variable called temp
start=p; //set the address of the new node to start i.e. insert new node at the beginning
p->next=temp; //make the new node created (2)point to the previous first node(3)
}}
Inserting at the end
• Here we simply need to make the
next pointer of the last node
point to the new node
void insert_end(node* p){ //p is the new node to be inserted
node *q=start; //declares q as the pointer pointing to the head or start i.e. points to the first
element of the linked list
if(start==NULL) //because the last element of a SLL points ALWAYS points to NULL, if then the
value of q or pointer pointing to the head is NULL
{
start=p; //insert the new node p at the end of the SLL which was formerly NULL
cout<<”\n Node inserted successfully at the end…!!!\n”;
}
else{ //if start however not equal to NULL loop till you get to a point where it is NULL
while(q->link!=NULL) //thus while q is NOT pointing to NULL i.e. (q isn’t the last node)
q=q->link; //traverse the list until q is the last node.
q->next=p; //insert the new node then q at the last node
}
}
• Here we again need to do 2 Inserting after an
steps :-
element
• (a)Make the next pointer of
the node to be inserted point
to the next node of the node
after which you want to insert
the node

• (b)Make the next pointer of


the node after which the node
is to be inserted, point to the
node to be inserted
void insert_after(int c, node* p) //This function takes 2 arguments position where to insert a node (c)
and the new node to be inserted (p)
{
node* q; //declares q as the pointer variable
q=start; //q is then initialized to start i.e. point at the first element of the SLL
for(int i=1;i<c; i++){
q=q->link; //starting at the first node loop till pointer q reaches position of insertion i.e. c
if(q==NULL) //if q gets to the end of the list without finding c
cout<<”Less than “<<c<<” nodes in the list…!!!”;
}
p->link=q->link; //(a)The link part of p(the node to be inserted) is made to point to the link part node of the
node after which we want to insert the node (i.e. the node q is pointing to).NB read from Left to Right

q->link=p; //(b)make the link part of q point to the new node


cout<<”\n Node inserted successfully”;
}
Basic Operations on a Linked List
1. Creating a List
2. Inserting an element in a list
3. Deleting an element from a list
4. Searching a list
5. Reversing a list
Deleting the first node
• Here we apply 2 steps:-
• Making the start pointer point towards the 2nd node
• Deleting the first node using delete keyword
void del_first(){
if(start==NULL)
cout<<”\n Error……List is empty\n”;
else{
node* temp=start;
start = temp->link;
delete temp;
cout<<”\n First node deleted successfully….!!!”;
}}
Deleting the last node
• Here we apply 2 steps:-
• Making the second last node’s next pointer point to NULL
• Deleting the last node via delete keyword
void del_last( ){
if(start==NULL)
cout<<”\n Error….List is empty”;
else{
node* q=start;
while(q->link->link!=NULL)
q=q->link;
node* temp=q->link;
q->link=NULL;
delete temp;
cout<<”\n Deleted successfully…”; }}}
Deleting a Particular Node
• Here we make the next pointer of the node previous to the node
being deleted ,point to the successor node of the node to be
deleted and then delete the node using delete keyword
void del(int c){
node* q=start;
for(int i=2;i<c;i++){
q=q->link;
if(q==NULL)
cout<<“\n Node not found\n”;
}
if(i==c){
node* p=q->link; //node to be deleted
q->link=p->link; //disconnecting the node p
delete p;
cout<<“Deleted Successfully”;
}}
Basic Operations on a Linked List
1. Creating a List
2. Inserting an element in a list
3. Deleting an element from a list
4. Searching a list
5. Reversing a list
Searching a SLL
• Searching involves finding the required element in the list

• We can use various techniques of searching like linear search or binary


search where binary search is more efficient in case of Arrays

• But NOT in case of linked list since random access is NOT available it would
become complex to do binary search in it

• We can thus perform a simple linear search traversal. In linear search each
node is traversed till the data in the node matches with the required value
void search(int x){
node*temp=start;
while(temp!=NULL){
if(temp->data==x){
cout<<“FOUND ”<<temp->data;
break;
}
temp=temp->next;
}
}
Basic Operations on a Linked List
1. Creating a List
2. Inserting an element in a list
3. Deleting an element from a list
4. Searching a list
5. Reversing a list
Reversing a linked list
• We can reverse a linked list by reversing the direction of the
links between 2 nodes
Reversing a linked list(2)
• We make use of 3 structure pointers say p,q,r. At any instant q will
point to the node next to p and r will point to the node next to q
• For next iteration p=q and q=r
• At the end we will change head to the last node
void reverse( ){ while(q!=NULL){
node*p,*q,*r; r=q->link;
if(start==NULL){ q->link=p;
cout<<"\n List is empty\n"; p=q;
return; q=r;
} }
p=start; start=p;
q=p->link; cout<<"\n Reversed successfully";
p->link=NULL; }
Some Applications of Linked List
1. The cache in your browser that allows 6. Image viewer – Previous and next
you to hit the BACK button (a linked list images are linked, hence can be
of URLs) accessed by next and previous button.

2. Undo functionality in Photoshop or Word 7. Music Player – Songs in music player are
(a linked list of state) linked to previous and next song. you
can play songs either from starting or
3. Linked list are used as a building block for ending of the list.
many other data structures such as 8. Maintaining directory of names.
stacks, queues, hash tables, binary trees
etc.
9. Performing arithmetic operations on
4. representing sparse matrices long integers.

5. Manipulation of polynomials by storing 10. Dynamic memory allocation : We use


constants in the node of linked list linked list of free blocks.
Linked Lists Summary
• The principal benefit of a linked list over a conventional array is that the list elements can
be easily inserted or removed without reallocation or reorganization of the entire
structure because the data items need not be stored contiguously in memory or on disk,
while restructuring an array at run-time is a much more expensive operation.

• Linked lists allow insertion and removal of nodes at any point in the list, and allow doing
so with a constant number of operations by keeping the link previous to the link being
added or removed in memory during list traversal.

• On the other hand, since simple linked lists by themselves do not allow random access to
the data or any form of efficient indexing, many basic operations—such as obtaining the
last node of the list, finding a node that contains a given datum, or locating the place
where a new node should be inserted—may require iterating through most or all of the
list elements.

You might also like