/* Program to create a singly linked list */
/* Linked list is a collection of Nodes, each node is going to store address of other Node*/
/* Node is self-referential class */
#include<iostream.h>
#include<stdlib.h>
class Node
{
public:
int data;
Node *next;
Node * createNode();
};
Node * Node:: createNode()
{
Node * temp;
temp=new Node;
temp->next=NULL;
cout<<"\n Enter Data:";
cin>>temp->data;
return temp;
}
typedef Node * List;
class SList : public Node
{
public:
List createList();
void printList(List);
List insertAtFront(List);
void insertNode(List);
List deleteFromFront(List);
Node *find(int , List);
Node *findPrev(int, List);
void deleteNode(List);
};
Node * SList :: findPrev(int x, List start)
{
while(start->next!=NULL)
{
if(start->next->data==x){ return start; }
start=start->next;
}
return NULL;
}
void SList :: deleteNode(List prev)
{
Node *temp;
temp=prev->next;
prev->next=prev->next->next;
delete(temp);
}
Node * SList :: find(int x, List start)
{
while(start!=NULL)
{
if(start->data == x) { return start; }
start=start->next;
}
return NULL;
}
/* Inserts the after specified Node*/
void SList :: insertNode(List pos)
{
Node *temp;
temp=createNode();
temp->next=pos->next;
pos->next=temp;
}
List SList :: insertAtFront(List start)
{
Node *temp;
temp=createNode();
temp->next=start;
return temp;
}
List SList :: deleteFromFront(List start)
{
Node *temp;
temp=start;
start=start->next;
delete(temp);
return start;
}
List SList :: createList()
{
char ch;
Node *temp;
List head, tail;
temp=createNode();
head=tail=temp;
cout<<"\n Do you want to continue (Y/y):";
cin>>ch;
while((ch=='Y')||(ch=='y'))
{
temp=createNode();
tail->next=temp;
tail=tail->next;
cout<<"\n Do you want to continue (Y/y):";
cin>>ch;
}
return head;
}
void SList :: printList(List start)
{
cout<<"\n List is :\n";
while(start!=NULL)
{
cout<<start->data<<" -> ";
start=start->next;
}
cout<<"NULL";
}
void main()
{
SList ob;
int x, op;
char ch;
List first, pos;
cout<<"\n Enter First List Data:";
first=ob.createList();
ob.printList(first);
while(1)
{
cout<<"\n Enter \n 1.for Insert \n 2. for Delete \n 3. for Exit";
cin>>op;
switch(op)
{
case 1: cout<<"\n Do you want to insert at front(Y/y):";
cin>>ch;
if((ch=='Y')||(ch=='y'))
{
first=ob.insertAtFront(first);
}
else
{
cout<<"\n after which element you wnat to insert the new data";
cin>>x;
pos=ob.find(x , first);
if(pos!=NULL)
{
ob.insertNode(pos);
}
else
{
cout<<"\n element is not found in the list";
}
}
breakk;
case 2: cout<<"\n Enter the element to be deleted:";
cin>>x;
if(first->data==x)
{
first=ob.deleteFromFront(first);
}
else
{
pos=ob.findPrev(x,first);
if(pos!=NULL) { ob.deleteNode(pos); }
else{ cout<<"\n No node with data value :"<<x; }
}
break;
case 3: exit(1);
default : cout<<"\n Enter right choice"; break;
}
ob.printList(first);
}
}