Data Structure Lecture 2 (1)
Data Structure Lecture 2 (1)
Lecture 2
Linked Lists
• Linked Lists
• A linked list is a list of items, called nodes, in which the order of the nodes is
determined by the address connected by pointer links hence, called a link,
stored in each node.
• A linked list is accessed via a pointer to the first node of the list.
• Each subsequent node is accessed via the link-pointer member stored in the
previous node.
• By convention, the link pointer in the last node of a list is set to null (0) to
mark the end of the list.
Lecture 2 DR. Mohamed Eassa
3
Linked Lists
•Data is stored in a linked list dynamically each node is created as
necessary.
•A node can contain data of any type, including objects of other classes.
Node components
• Data: stores relevant information
• Next(Link): stores address
Head (first)
Address of the first node in the list
Arrow points to node address
Stored in node
Down arrow in last node indicates NULL link field
Head Null
Head Null
10 20 30 40 50 Null
10 20 30 40 50 Null
10 20 30 40 50 Null
void display ()
{
node* temp = head;
while(temp!= NULL)
{
cout << temp->data<<“ ”;
temp = temp -> next;
}
}
Head
10 20 30 40 50 Null
Temp
void deleteFirst()
{
if(isempty())
cout<<"Already Empty \n";
else
{
node* temp = head;
head = head-> next; (or) head = temp-> next;
delete temp;
}
}
Null 10 20 30 40 50 Null
else
void delete (int item) {
{ node* prev= NULL;
if(isempty()) node* delptr= head;
cout<<"Already Empty \n"; while (delptr->data != item)
If (head-> data== item) {
{ prev = delptr;
node* temp= head; delptr = delptr-> next;
head = head->next; //(or) head = temp-> next; }
delete temp; Prev->next = delptr->next;
} Delete delptr;
}
Lecture 2 DR. Mohamed Eassa } 19
Searching
10 20 30 40 50 Null
Int main()
{
linkedlist list;
if(list.isempty())
cout<< “the list is empty” \n;
int item;
cout << “enter item to in the list” \n;
cin >> item;
list. insertFirst(item);
list.display();
} 21
Lecture 2 DR. Mohamed Eassa