How to delete a node from the start of linked list
DeleteFromStart() deletes the first node in the linked list.
Summary of DeleteFromStart()
First of all the linked list is checked whether it is empty or not. If it is empty, then the if part will execute and displays the message, else in case if the linked list is not empty then the else part will execute – first a new node tptr is created and is assigned the head pointer, after that the head is moved to the next node and at the last the tptr (which is containing the previous head) is deleted. Hence the firs node of the linked list is deleted.
Code of DeleteFromStart()
void LinkList::DeleteFromStart()
{
if(head==NULL)
{
cerr<<"Linked List already empty"<<endl;
}
else
{
Node*tptr=head;
head=head->link;
delete tptr;
}
}
Code
#include "stdafx.h"
#include "iostream"
#include "conio.h"
using namespace std;
struct Node
{
public:
int data;
Node*link;
Node();
};
Node::Node()
{
data=0;
link=NULL;
}
class LinkList
{
public:
Node*head;
LinkList();
void AddNodeAtEnd(int);
void DeleteFromStart();
void DisplayWhole();
};
LinkList::LinkList()
{
head=NULL;
}
void LinkList::AddNodeAtEnd(int _data)
{
Node*node=new Node();
node->data=_data;
node->link=NULL;
if(head==NULL)
head=node;
else
{
Node*tptr=head;
while(tptr->link!=NULL)
tptr=tptr->link;
tptr->link=node;
}
}
void LinkList::DeleteFromStart()
{
if(head==NULL)
{
cerr<<"Linked List already empty"<<endl;
}
else
{
Node*tptr=head;
head=head->link;
delete tptr;
}
}
void LinkList::DisplayWhole()
{
Node*temp=head;
while(temp!=NULL)
{
cout<<temp->data<<endl;
temp=temp->link;
}
}
int main()
{
LinkList l;
// Adding first element to end of the linked list
l.AddNodeAtEnd(10);
// Adding second element to end of the linked list
l.AddNodeAtEnd(20);
// Adding third element to end of the linked list
l.AddNodeAtEnd(30);
// Adding fourth element to end of the linked list
l.AddNodeAtEnd(40);
// Adding fifth element to end of the linked list
l.AddNodeAtEnd(50);
// Displaying all nodes in the linked list
cout<<"Linked list : "<<endl;
l.DisplayWhole();
cout<<endl;
l.DeleteFromStart();
// Displaying all nodes in the linked list
cout<<"Linked list after deleting the first node : "<<endl;
l.DisplayWhole();
cout<<endl;
_getche();
return 0;
}
Output
Linked list :
10
20
30
40
50
Linked list after deleting the first node :
20
30
40
50
0 comments:
Post a Comment