Different Operations on Linked List.
//program to use linked list
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
struct node
{
int data;
node *link;
};
node *start=NULL,*next;
node *ptr;
node* createNode(int value)
{
node *newnode;
if(start==NULL)
{
newnode=new node;
start=newnode;
start->data=value;
start->link=NULL;
next=start;
}
else
{
newnode=new node;
newnode->data=value;
newnode->link=NULL;
next->link=newnode;
next=newnode;
}//end of else
}//end of function
void input()
{
int value;
cout<<"Enter value:";
cin>>value;
}//end of function
void display()
{
ptr=start;
cout<<endl<<"Elements of List are :"<<endl;
while(ptr!=NULL)
{
cout<<endl<<ptr->data;
ptr=ptr->link;
}
}//end of function display
void search(int value)
{
int found=0;
ptr=start;
while(ptr!=NULL)
{
if(ptr->data==value)
{
found=1;
cout<<value<<" found in the list";
}
ptr=ptr->link;
}//end of while
if(found==0)
{
cout<<endl<<value<<" Not found in the list";
}
}//end of search function
void deleteNode()
{
}//end of delete node
void insertNodeAtFirst(int value)
{
node *newnode;
newnode=new node;
newnode->data=value;
newnode->link=start;
start=newnode;
}//end of function
int countNodes()
{
int ctr=0;
if(start!=NULL)
{
ptr=start;
while(ptr!=NULL)
{
ctr++;
ptr=ptr->link;
}
return ctr;
}//end if
return ctr;
}//end of function
void insertAt(int pos,int value)
{
ptr=start;
int ctr=0;
node *newnode;
while(ptr!=NULL)
{
ctr++;
if(ctr==pos-1)
{
newnode=new node;
newnode->data=value;
newnode->link=ptr->link;
ptr->link=newnode;
}
ptr=ptr->link;
}
}//end of function
int main()
{
int choice,value,pos=0;
do
{
cout<<"Add--------->1"<<endl;
cout<<"Display----->2"<<endl;
cout<<"Exit-------->3"<<endl;
cout<<"Clear Screen-->4"<<endl;
cout<<"Search------->5"<<endl;
cout<<"Insert node at First------>6"<<endl;
cout<<"Insert node in Middle------>7"<<endl;
cout<<"Enter your choice :";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Enter value:";
cin>>value;
createNode(value);
break;
case 2:
display();
break;
case 3:
exit(1);
break;
case 4:
system("cls");
break;
case 5:
cout<<"Enter value to search:";
cin>>value;
search(value);
break;
case 6:
cout<<"Enter value:";
cin>>value;
insertNodeAtFirst(value);
break;
case 7:
cout<<"Enter value:";
cin>>value;
cout<<"Enter position:";
cin>>pos;
insertAt(pos,value);
break;
}//end of switch
}while(1);
}//end of main