以下代码参考晴神宝典
#include
#include
using namespace std;
struct node{
int data;
node* next;
};
node* create(int a[],int n)
{
node* pre,p,head;
head=new node;
head->next=NULL;
pre=head;
for(int i=0;i<n;i++)
{
p=new node;
p->data=a[i];
p->next=NULL;
pre->next=p;
pre=p;
}
return head;
}
void display(node head)
{
while(head)
{
printf("%d ",head->data);
head=head->next;
}
}
int search(node head,int x)
{
int count;
node* p=head->next;
while§
{
if(p->datax)
{
count++;
}
p=p->next;
}
return count;
}
void insert(node* head,int pos,int x)
{
node* p=head;
for(int i=0;i<pos-1;i++)
{
p=p->next;
}
node* q=new node;
q->data=x;
q->next=p->next;
p->next=q;
}
void del(node* head,int x)
{
node* p=head->next;
node* pre=head;
while§
{
if(p->datax)
{
pre->next=p->next;
delete§;
p=pre->next;
}
else
{
pre=p;
p=p->next;
}
}
}
int main()
{
int a[10010];
cout<<“please input lianbiao numbers:”;
int r;
cin>>r;
cout<<“please input lianbiao order:”;
for(int i=0;i<r;i++)
{
cin>>a[i];
}
node* L=create(a,r);
L=L->next;
cout<<“plesa input operation numbers:”;
int n;
cin>>n;
switch(n)
{
case 1:cout<<“lianbiao order:”;
display(L);
break;
case 2:cout<<“please input search number:”;
int i;
cin>>i;
printf("%d",search(L,i));
break;
case 3:int pos;
int m;
cout<<“please input insert location and number:”;
cin>>pos>>m;
insert(L,pos,m);
display(L);
break;
case 4:int p;
cin>>p;
cout<<“please input del number:”;
del(L,p);
display(L);
break;
default:printf(“error”);
}
return 0;
}
单链表的基本操作
最新推荐文章于 2024-10-16 10:13:45 发布