Singly Link List
Singly Link List
Singly Link List
struct node
{ int data;
node *next;
};
class list{
node *head;
node *tail;
public:
list()
head=NULL;
tail=NULL;
void insert()
int item;
cin>>item;
temp->data=item;
temp->next=NULL;
if(head==NULL)
{
head=temp;
tail=temp;
else{
tail->next=temp;
tail=temp;
void insertfirst()
int item;
cin>>item;
temp->data=item;
temp->next=head;
head=temp;
void insertlast()
int item;
cin>>item;
node *temp,*temp1;
temp=new node;
temp1=head;
while(temp1->next!=NULL)
temp1=temp1->next;
temp1->next=temp;
temp->data=item;
temp->next=NULL;
void insertposition()
int item,p;
cin>>p;
cout<<endl;
cin>>item;
temp->data=item;
node *cur;
node *pre;
cur=head;
for(int i=1;i<p;i++)
pre=cur;
cur=cur->next;
}
temp->next=cur;
pre->next=temp;
void display()
node *temp;
temp=head;
if(head!= NULL)
while(temp!=NULL)
cout<<temp->data<<"--->";
temp=temp->next;
void displaybackward()
// Store next
next = current->next;
current->next = prev;
// Move pointers one position ahead.
prev = current;
current = next;
head = prev;
void updatenode()
int item,p;
cin>>p;
cout<<endl;
cin>>item;
node *temp;
temp=head;
for(int i=1;i<p;i++)
temp=temp->next;
temp->data=item;
void deletestart()
{ if(head==NULL)
{
cout<<"list emty\n"; }
else
{ head=head->next; }
void deletend()
node *cur,*temp;
temp=head;
while(temp->next!=NULL)
cur=temp;
temp=temp->next;
cur->next=NULL;
void deleteposition()
int p;
cin>>p;
cout<<endl;
node *cur,*pre;
cur=head;
for(int i=1;i<p;i++)
{pre=cur;
cur=cur->next;
}
pre->next=cur->next;
void searchnode()
int item;
cin>>item;
node *temp,*cur;
temp=head;
if(head==NULL)
cout<<"list is empty\n";
else
while(temp!=NULL)
{ if(temp->data==item)
return;
//cur=temp;
temp=temp->next;
}
}
void sortList() {
*cur = NULL;
int t;
if(head == NULL) {
cout<<"list is empty"<<endl;
return; }
else {
while(temp != NULL) {
cur = temp->next;
while(cur != NULL) {
t = temp->data;
temp->data = cur->data;
cur->data = t; }
cur = cur->next; }
};
int main()
list l;
int choice;
int n;
do{
cout<<"PRESS 1 TO INSERT NODE\nPRESS 2 TO INSERT NODE AT FIRST"<<endl;
cin>>choice;
switch(choice)
case 1:
cin>>n;
for(int i=1;i<=n;i++)
l.insert();
break;
case 2:
l.insertfirst();
break;
case 3:
l.insertlast();
break;
case 4:
l.insertposition();
break;
case 5:
l.deletestart();
break;
case 6:
l.deletend();
break;
case 7:
l.deleteposition();
break;
case 8:
l.searchnode();
break;
case 9:
l.sortList();
break;
case 10:
l.updatenode();
break;
case 11:
l.display();
break;
case 12:
l.displaybackward();
break;
default:
cout<<"invalid entry"<<endl;
}while(choice!=0);
return 0;