data structure lab 03ameer hamza
TRANSCRIPT
MILITARY COLLEGE OF SIGNALS, NUST
2015
data structure lab 03 to SIR HAMMAD
AMEER HAMZA MUHAMMAD MUNEEB MALIK
bete 51 -C
R A W A L P I N D I , P A K I S T A N
Question NO. 1 all parts in one....
#include<iostream.h>
#include<conio.h>
struct node{
node *next;
int data;
};
class list{
private:
node *head,*temp,*temp1,*temp2,*temp3;
public:
list(){
head=NULL;
}
//----------------------------------------create---------------
void create(){
int y,u;
cin>>u;
for(int i=0;i<u;i++){
if(head==NULL){
temp=new node();
cout<<"enter the node value\t:";
cin>>y;
temp->data=y;
temp->next=NULL;
head=temp;
}
else{
temp=new node();
cout<<"enter the node value\t:";
cin>>y;
temp->data=y;
temp->next=NULL;
temp1=head;
while(temp1->next!=NULL){
temp1=temp1->next;
}
temp1->next=temp;
}
}
temp->next=head;
}
//--------------------------------------------display--------
void display(){
temp1=head;
int ai=0;
while(ai!=20){
cout<<temp1->data<<endl;
temp1=temp1->next;
ai++;
}
}
//-------------------------------------------traverse--------
void tra(){
int ty,con=0,tr=0;
temp2=head;
while(temp2->next!=head){
con++;
temp2=temp2->next;
}
temp2=head;
cout<<"enter the position to traverse from\t:";
cin>>ty;
for(int i=0;i<ty;i++){
temp2=temp2->next;
}
for(int i=0;i<=con;i++){
cout<<"traversed\t:"<<temp2->data<<endl;
temp2=temp2->next;
}
}
//-------------------------------------------delete-----------
void del(){
int o,dat,q=0;
cout<<"enter the position\t:";
cin>>o;
if(o==1){
temp1=head;
temp3=head;
while(temp3->next!=head){
temp3=temp3->next;
}
head=head->next;
temp3->next=head;
delete temp1;
}
else{
temp2=head;
while(temp2->next!=head){
q++;
temp2=temp2->next;
}
if(o==q){
temp3=head;
while(temp3->next!=head){
temp2=temp3;
temp3=temp3->next;
}
temp2->next=head;
delete temp3;
}
else{
temp1=head;
temp2=temp1;
for(int i=0;i<o-1;i++){
temp2=temp1;
temp1=temp1->next;
}
temp3=temp1;
temp1=temp1->next;
temp2->next=temp1;
delete temp3;
}
}
}
//-------------------------------------------insert-----------
void insert(){
int c=1, e,da;
cout<<"enter the position\t:";
cin>>e;
temp1=head;
if(e==1){
temp=new node();
cout<<"enter the value\t:";
cin>>da;
temp->data=da;
temp3=head;
while(temp3->next!=head){
temp3=temp3->next;
}
temp->next=temp1;
head=temp;
temp3->next=head;
}
else{
temp2=head;
while(temp2->next!=head){
c++;
temp2=temp2->next;
}
if(e==c){
temp=new node();
cout<<"enter the value\t:";
cin>>da;
temp->data=da;
temp1=head;
while(temp1->next!=head){
temp1=temp1->next;
}
temp1->next=temp;
temp->next=head;
}
else{
temp=new node();
cout<<"enter the value\t:";
cin>>da;
temp->data=da;
temp1=head;
for(int i=0;i<e-1;i++){
temp2=temp1;
temp1=temp1->next;
}
temp2->next=temp;
temp->next=temp1;
}
}
}
};
int main(){
list a;
a.create();
a.insert();
a.display();
a.del();
a.display();
a.tra();
getch();
}
RESULT: