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

Lec 4 Iinked List

This document covers the concepts of linked lists in data structures, including their dynamic memory allocation and operations in C++. It contrasts linked lists with arrays, highlighting their advantages in terms of flexibility and memory efficiency. The document also details the implementation of linked lists in C++, including node definition, insertion, deletion, and traversal methods.

Uploaded by

moh.s.hafez.2010
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views29 pages

Lec 4 Iinked List

This document covers the concepts of linked lists in data structures, including their dynamic memory allocation and operations in C++. It contrasts linked lists with arrays, highlighting their advantages in terms of flexibility and memory efficiency. The document also details the implementation of linked lists in C++, including node definition, insertion, deletion, and traversal methods.

Uploaded by

moh.s.hafez.2010
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/ 29

(ELE 144)

Data Structures and Algorithms

Lecture 4
Linked list

Instructor:
DR. Nada El-Meligy
Dynamic Memory Allocation
Agenda
Introduction to linked list

Array versus linked list

Linked lists operations in C++

• Traversing a list
• Insertion item.
Dynamic Memory
Allocation
Problems with normal array variable declaration

int main()
{
int A[10]; // Fixed size
int B[n]; // Error ..Size must be known at compile time.
}
Main Memory
• Our program when loaded into main memory is divided into 4
segments: CODE, DATA, STACK, Heap.
• A data segment contains the global variables and static variables.
• A code segment contains the executable instructions.
• A stack segment store all the auto variables. Also, Used for function
call’s return, addresses, arguments and local variables.
• Hence a stack is an area of memory for storing data temporarily.
Heap and Stack
• Allocation and deallocation of memory in this area is done automatically.
• Heap segment is for dynamic memory management.
• It is for the programmers to manage.
• We can allocate memory when you feel the need for it and delete when you
feel that the memory is no longer needed.
• And it is responsibility of the programmer to delete memory when no longer
needed.
• Hence for array we can dynamically allocate memory of size which can be
determined at run time.
• In C++ we use new and delete.
Heap and Stack (Cont.)
int main()
{ int I;
float *ptr;
cout<<"Enter array size ";
cin>>I;
ptr=new float[I];
cout<<"Enter your elements:"<<endl;
for (int k=0;k<I;k++)
cin>> *(ptr+k);
cout<<"the elements in array:"<<endl;
for (int k=0;k<I;k++)
cout<< *(ptr+k)<<endl;
delete [] ptr;
return 0;}
Linked List
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? …
}
Then you have to
reserve enough slots
• Arrays are suitable for for the largest possible
case.
▪ Inserting/deleting an element at the end. And what if you arrayName
10
need to insert
0

15
▪ Randomly accessing any element(easy access to any a new item in
1

2 20

the middle of an array?


3 22
element a[i] in constant time ). 4 25
5 30

We have to move every 6 35


▪ Searching the list for a particular value. item below the insertion
7 40
8 45
spot down by one! 9 50
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.

▪ 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!
Single Linked List Implementation
Type of linked list is 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
class node
To allocate new nodes:
{ Data
int data; /* Data */ node *new_node = new node();
node *next; /* pointer*/ next
} ;
To change/access a node p’s value:
new_node->data = 10;
cout << new_node->data;
To make node p link to another node
To make node q a “terminal” node: that’s at address q:
q->next = NULL; new_node->next = q;
Example 1: Illustration
class LL
class node
{public:
{public:
node *head;
string name;
LL()
int age;
{
node *next;
head=NULL;
};
}};

Also assume the list with three


head
nodes n1, n2 and n3 for 3 students.
name
node* n1 = new node(); age
node* n2 = new node(); next NULL
node* n3 = new node(); n1 n2 n3
int main()
class node {
{public: LL l1;
string name; node *n1=new node();
int age; node *n2=new node();
node *next; node *n3=new node();
};
l1.head=n1;
n1->next=n2;
n1->name="Ahmed";
n1->age=10;
class LL
{public: n2->next=n3;
node *head; n2->name="mohamed";
LL() n2->age=20;
{
head=NULL; n3->next=NULL;
}}; n3->name="samy";
n3->age=30;
}
• To start with, we have to create a node (the first node), and make
head point to it.

node *n1= new node();


n1->data = data; //Links the data field with data
n1->next = NULL; //Links the address field to NULL
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.
node *n1= new node();
node *n2= new node();
node *n3= new node();
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.
• Searching an item in the list.
• Count number of items in the list.
• 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, Traversal: given a pointer
• Follow the pointers. to the first node of the list,
step through the nodes
• Display the contents of the nodes as they are traversed. of the list
• Stop when the next pointer points to NULL.

The function show()is given. This function to be called from main() function as:
void show()
{
node* 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: searching an item in the list (search function)
bool search(int item)
{
node* temp = head;
while(temp!= NULL)
{ if (temp->data==item)
return true;
temp= temp->next; //Advances the position of current node
}
return false;
}

Single Linked List: count number of items in the list.(count function)


int count()
{ int counter =0;
node* temp = head;
while(temp!= NULL)
{ counter++;
temp= temp->next; //Advances the position of current node
}
return counter;
}
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 Insert_add_first(int val)


{
node *new_node=new node();
New_node->data=val;
if (IsEmpty())
{
new_node->next=NULL;
}
else
{
new_node->next=head;
}
head=new_node;
}
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(int val)


{if (IsEmpty())
Insert_add_first(val);
else
{
node *temp=head; //Traverse to the last node
while(temp->next!=NULL)
{
temp=temp->next;
}
node *new_node=new node();
new_node->data=val;
new_node->next=NULL;
temp->next=new_node;
}

}
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(int item, int val)
{
If (IsEmpty())
Insert_add_first(val);
else
{if (search(item))
{
node *new_node=new node();
new_node->data=val;
node *temp=head;
while(temp->next->data!=item)
{
temp=temp->next;
}
new_node->next=temp->next;
temp->next=new_node;
}
else
cout<<“sorry, item not found”;
}
}

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