用c语言创建一个链表,包含身高和体重两个变量分别赋五个值,然后对链表进行数组插入,数组删除,数组排序最后输出链表
时间: 2024-03-13 09:29:42 浏览: 13
#include<stdio.h>
#include<stdlib.h>
struct node{ //定义链表结构体
float height;
float weight;
struct node *next;
};
struct node *create(int n){ //创建链表函数
struct node *head=NULL,*p=NULL,*tail=NULL;
int i;
float h,w;
for(i=0;i<n;i++){
printf("请输入第%d个节点的身高和体重(空格隔开):",i+1);
scanf("%f %f",&h,&w);
p=(struct node *)malloc(sizeof(struct node));
p->height=h;
p->weight=w;
if(head==NULL){
head=p;
tail=p;
}
else{
tail->next=p;
tail=p;
}
}
tail->next=NULL;
return head;
}
struct node *insert(struct node *head, int n){ //数组插入函数
struct node *p=NULL,*q=NULL,*s=NULL;
float h,w;
int i;
printf("请输入要插入的位置:");
scanf("%d",&n);
printf("请输入要插入的身高和体重(空格隔开):");
scanf("%f %f",&h,&w);
s=(struct node *)malloc(sizeof(struct node));
s->height=h;
s->weight=w;
if(n==1){
s->next=head;
head=s;
}
else{
p=head;
for(i=1;i<n;i++){
q=p;
p=p->next;
}
s->next=p;
q->next=s;
}
return head;
}
struct node *del(struct node *head, int n){ //数组删除函数
struct node *p=NULL,*q=NULL;
int i;
printf("请输入要删除的位置:");
scanf("%d",&n);
if(n==1){
p=head;
head=p->next;
free(p);
}
else{
p=head;
for(i=1;i<n;i++){
q=p;
p=p->next;
}
q->next=p->next;
free(p);
}
return head;
}
struct node *sort(struct node *head){ //数组排序函数
struct node *p=NULL,*q=NULL;
float h,w;
for(p=head;p!=NULL;p=p->next){
for(q=p->next;q!=NULL;q=q->next){
if(p->weight>q->weight){
h=p->height;
w=p->weight;
p->height=q->height;
p->weight=q->weight;
q->height=h;
q->weight=w;
}
}
}
return head;
}
void print(struct node *head){ //输出链表函数
struct node *p=NULL;
printf("链表中节点的身高和体重分别为:\n");
for(p=head;p!=NULL;p=p->next){
printf("%.2f %.2f\n",p->height,p->weight);
}
}
int main(){
struct node *head=NULL;
int n=5,opt;
head=create(n);
printf("链表创建成功!\n");
while(1){
printf("\n请选择要进行的操作:\n");
printf("1.数组插入节点\n");
printf("2.数组删除节点\n");
printf("3.数组排序节点\n");
printf("4.输出链表节点\n");
printf("5.退出程序\n");
scanf("%d",&opt);
switch(opt){
case 1:
head=insert(head,n);
n++;
break;
case 2:
head=del(head,n);
n--;
break;
case 3:
head=sort(head);
printf("排序完成!\n");
break;
case 4:
print(head);
break;
case 5:
printf("程序已退出!\n");
exit(0);
break;
default:
printf("输入有误,请重新输入!\n");
break;
}
}
return 0;
}