建立单向动态链表,并对它进行插入、删除和输入等操作,包括以下任务:

2024-11-28 02:07:33
推荐回答(1个)
回答(1):

#include
#define LEN sizeof(struct number)
struct number /*定义编号和数字*/
int name;
int num;
struct number * next;
};

struct number * create() /*建立链表函数*/
{
struct number * head,* new,* tail,* p;
int count=0;
while(1)
{
new=(struct number *)malloc(LEN);
printf("input Name and Number\n");
scanf("%d %d",&new->name,new->num); /*用户输入编号和数字*/
if(new->name==0)
{
free(new);
break;
}
else if(count==0)
{
head=new;
tail=new;
}
else
{
tail->next=new;
tail=new;
}
count++;
}
tail->next=NULL;
return(head);
}

struct number * delist(struct number *head,int name) /*删除数字的函数*/
{
struct number * p0,* p1;
p1=head;
if(head==NULL)
{
printf("\nempty list!\n");
}
else
if(p1->name==name) /*找到相同编号*/
head=p1->next;
else
{
while(p1->name!=name&&p1->next!=NULL) /*逐一排查*/
{
p0=p1;
p1=p1->next;
}
if(p1->name==name)
{
p0->next=p1->next;
printf("The node is deleted\n");
}
else
printf("The node can not been foud!\n");
}
return head;
}

struct number * insert(struct number * head,struct number * new)
{ /*插入函数*/
struct number * p0,* p1;
p1= head;
if(head==NULL)
{
head=new;
new->next=NULL;
}
else
if(new->namename) /*寻找新数字适合的位置插入*/
{
new->next=head;
head=new;
}
else
{
while(new->name>p1->name)
{
p0=p1;
p1=p1->next;
}
new->next=p0->next;
p0->next=new;
}
return(head);
}

void print(struct number * head) /*打印函数*/
{
struct number * p;
p=head;
if(head==NULL) /*其实用不到*/
printf("list is empty\n");
else
while(p!=NULL)
{
printf("%d%d\n",p->name,p->num); /*打印链表内容*/
p=p->next;
}
}

struct number * find(struct number * head,struct number * new)
{ /*查询函数*/
struct number * p0,* p1;
p1= head;
if(head==NULL)
{
head=new;
new->next=NULL;
}
else
if(new->name!=p1->name) /*寻找和输入编号相同的节点,不是则往下读*/
{
new->next=head;
head=new;
}
else
{
while(new->name==p1->name)
{
printf(”find successfully!\n”);
printf(“%d %d”,p1->name,p1->num);
}

}
return(head);
}

void main() /*主函数*/
{
struct number * head,* p;
int name;
head=create(); /*往下逐一调用函数*/
print(head);
printf("Input the delete number:");
scanf("%d",&name);
head=delist(head,name);
print(head);
printf("Input the inserted name and number:");
p=(struct number *)malloc(LEN);
scanf("&d&d",p->name,p->num);
head=insert(head,p);
print(head);
printf(“Input the found name:”);
scanf(“%d”,&name);
head=find(head,p);
print(head);

}

find函数你可以不用,在主函数中将find函数也一起删掉就行了。