1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
|
using namespace std;
#include<iostream>
#include<cstdio>
#include<conio.h>
struct node
{
int data;
struct node *link;
};
void append(struct node *,int);
void addatbeg(struct node *,int);
void addafter(struct node *,int,int);
void display(struct node *);
int count(struct node *);
void Delete(struct node *,int);
int main(void)
{
struct node *p;
p=NULL;
cout<<"No of elements in the linked list:"<<count(p);
append(p,14);
append(p,30);
append(p,25);
append(p,42);
append(p,17);
display(p);
addatbeg(p,999);
addatbeg(p,888);
addatbeg(p,777);
display(p);
addafter(p,7,0);
addafter(p,2,1);
addafter(p,5,99);
display(p);
cout<<"\nNo of elements in the linked list:"<<count(p);
Delete(p,99);
Delete(p,1);
Delete(p,10);
display(p);
cout<<"\nNo of elements in the linked list:"<<count(p);
cin.get();
getch();
return 0;
}
void append(struct node *q,int num)
{
struct node *temp,*r;
if(q==NULL)
{
temp= new struct node;
temp->data=num;
temp->link=NULL;
q=temp;
}
else
{
temp=q;
while(temp->link!=NULL)
temp=temp->link;
r= new struct node;;
r->data=num;
r->link=NULL;
temp->link=r;
}
}
void addatbeg(struct node *q,int num)
{
struct node *temp;
temp= new struct node;;
temp->data=num;
temp->link=q;
q=temp;
}
void addafter(struct node *q,int loc,int num)
{
struct node *temp,*r;
int i;
temp=q;
for(i=0;i<loc;i++)
{
temp=temp->link;
if(temp==NULL)
{
cout<<"\nThere are less than"<<loc<<"elements in the list";
return;
}
}
r= new struct node;;
r->data=num;
r->link=temp->link;
temp->link=r;
}
void display(struct node *q)
{
cout<<"\n";
while(q!=NULL)
{
cout<<q->data;
q=q->link;
}
}
int count(struct node *q)
{
int c=0;
while(q!=NULL)
{
q=q->link;
c++;
}
return c;
}
void Delete(struct node *q,int num)
{
struct node *old,*temp;
temp=q;
while(temp!=NULL)
{
if(temp->data==num)
{
if(temp==q)
q=temp->link;
else
old->link=temp->link;
delete temp;
return;
}
else
{
old=temp;
temp=temp->link;
}
}
cout<<"\nElement"<<num<<"not found";
}
| |