How to write sorted linked list program in cpp with class
C++ Program for sorted single linked list with class
//sorted linked list
latest
#include<iostream>
using namespace std;
struct node
{
int data;
node *next;
};
node *start=NULL;
void insert(int d)
{
node
*newnode=new node;
newnode->data=d;
newnode->next=NULL;
//insert as
first elt
if(start==NULL)
{
//start->next=newnode;
start=newnode;
}
//insert before
first elt
if(newnode->data
< start->data)
{
newnode->next=start;
start=newnode;
return;
}
//inserting at
middle
node* prev; node
*ptr;
for(prev=start,ptr=start->next;ptr;prev=ptr,ptr=prev->next)
{
if(newnode->data < ptr->data)
{
prev->next=newnode;
newnode->next=ptr;
return;
}
}
//inserting at
last
if(ptr==NULL)
{
prev->next=newnode;
newnode->next=NULL;//must
return;
}
}
void display()
{
node *ptr=start;
while(ptr!=NULL)
{
cout<<ptr->data<<" ";
ptr=ptr->next;//must else infinite loop
}
cout<<endl;
}
void deleteNode()
{
int key;
cout<<"Enter
elt to delete:"<<endl;
cin>>key;
//deleting the first
node
if(key==start->data)
{
node *temp;
temp=start;
start=start->next;
delete temp;
return;
}
//deleting middle
node
node *ptr; node
*prev;
for(prev=start,ptr=start->next;ptr;prev=ptr,ptr=prev->next)
{
if(ptr->data==key)
{
prev->next=ptr->next;
delete ptr;
return;
}
}
//deleteing last elt
means data not present
if(ptr==NULL)
{
cout<<"key
"<<key<<" Not present in LL.\n";
return;
}
if(start==NULL)
{
cout<<"No
Element to delete"<<endl;
return;
}
}
int main()
{
insert(10);
insert(4);
insert(8);
insert(9);
insert(6);
insert(7);
insert(25);
display();
deleteNode();
display();
deleteNode();
deleteNode();
deleteNode();
deleteNode();
deleteNode();
deleteNode();
deleteNode();
deleteNode();
deleteNode();
return 0;
}
/* Output:
$ ./a.out
4 6 7 8 9 10 25
Enter elt to delete:
100
key 100 Not present
in LL.
4 6 7 8 9 10 25
Enter elt to delete:
9
Enter elt to delete:
9
key 9 Not present in
LL.
Enter elt to delete:
10
Enter elt to delete:
4
Enter elt to delete:
25
Enter elt to delete:
6
Enter elt to delete:
7
Enter elt to delete:
8
No comments:
Post a Comment