Tuesday, 16 December 2014

Singly Link List

A program of Singly link list which function such as Insertion At Head, Insertion At Tail, Bubble Sort, Find function, Delete function, Print function 




#include<iostream>
using namespace std;

struct node{
int data;
node *next;
};
int count=0;
void insert_head(node **pointerToStart,node **pointerToTail,int n){
node *temp=new node;
temp->data=n;
if(*pointerToStart==NULL){
(*temp).next=*pointerToStart;
*pointerToStart=temp;
*pointerToTail=temp;
count++;
}
else{
(*temp).next=*pointerToStart;
*pointerToStart=temp;
count++;
}

}

void insert_tail(node **pointerToStart,node **pointerToTail,int n){
node *temp=new node;
temp->data=n;
if(*pointerToStart==NULL){
(*temp).next=*pointerToStart;
*pointerToStart=temp;
*pointerToTail=temp;
count++;
}
else{
(*pointerToTail)->next=temp;
temp->next=NULL;
*pointerToTail=temp;
count++;
}

}

bool find(node** pointerToStart,int n){
node* temp=*pointerToStart;
if(*pointerToStart==NULL){
return false;
}
while(temp!=NULL){
if(temp->data==n){
return true;
}
temp=temp->next;
}
return false;
}

void del(node** pointerToStart,int n){
node *previous=NULL,*current=*pointerToStart;
if(find(pointerToStart,n)==false){
cout<<"\nNo is not present in the list\n";
}
else{
if((*pointerToStart)->data==n){
*pointerToStart=current->next;
delete current;
cout<<"\n No deleted\n";
return;
}
else{
while(current!=NULL){
if(current->data==n){
previous->next=current->next;
delete current;
cout<<"\n No deleted\n";
return;
}
previous=current;
current = current->next;

}
}
}
}

void print_list(node** pointerToStart){
node* temp=*pointerToStart;
while(temp!=NULL){
cout<<temp->data<<"->";
temp=temp->next;
}
cout<<"NULL";
}

void bubleSort(node** pointerToStart){
int n=count;
node* temp,*current;
cout<<"\no of elements are = "<<n;
while(n--){

temp=*pointerToStart;
current=temp->next;
cout<<"\ncheck 1 ";
while(current!=NULL){
cout<<"\ncheck 2 ";
if(temp->data>temp->next->data){
int t=temp->data;
temp->data=temp->next->data;
temp->next->data=t;
}
temp=temp->next;
current=temp->next;
}

}
return;
}
main(){
int d;
int t=1;
node *start=NULL,*tail=NULL;
while(t=1){
//cout<<"\n";
cout<<"\nPress 1 to add at head";
cout<<"\nPress 2 to add at tail";
cout<<"\nPress 3 to search a no";
cout<<"\nPress 4 to print the list";
cout<<"\nPress 5 to delete";
cout<<"\nPress 6 to Buble Sort";
cout<<"\nPress 12 to exit\n";
int c;
cin>>c;
switch(c){
case 1 :
cout<<"enter data ";
cin >> d;
insert_head(&start,&tail,d);
break;

case 2 :
cout<<"enter data ";
cin >> d;
insert_tail(&start,&tail,d);
break;

case 3 :
cout<<"enter Number which you wana find ";
cin >> d;
if(find(&start,d)==true){
cout<<"\nNumber is present\n";
}
else{
cout<<"\nNumber is Not present\n";
}
break;

case 4 :
print_list(&start);
break;

case 5 :
cout<<"\nenter the no you wana delete  ";
cin>>d;
del(&start,d);
break;

case 6:
bubleSort(&start);
print_list(&start);
case 12 :
t=0;

}
}
}

No comments:

Post a Comment