一个人可用的链表操作

来源:互联网 发布:芝华仕沙发头等舱 知乎 编辑:程序博客网 时间:2024/04/30 17:24
#include<stdio.h>#include<stdlib.h>#include<string.h>/*定义一个存储学生信息的结构,也就是节点(节点就是结构)*/struct node{char name[10];int age;struct node *next;};/*对main函数中需要调用的方法函数进行声明*/struct node *creat(int n);void delet(struct node *head);void sort(struct node *head);void output(struct node *head);struct node *insert(struct node *new_node);void delet1(struct node *head);int main(void){int n;char cmd;struct node *head;printf("请输入需要的储存的学生信息数量:");scanf("%d",&n);for(;;){printf("\n\n开始创建链表请按:c\n按名删除信息请按:w\n按照年龄排序请按:s\n插入学生信息请按:i\n输出学生信息请按:p\n删除重复信息请按:d\n退出信息系统请按:q\n请输入指令:");scanf(" %c",&cmd);printf("\n");if(cmd=='s')sort(head);else if(cmd=='p')output(head);else if(cmd=='c')head=creat(n);else if(cmd=='w')delet1(head);else if(cmd=='d')delet(head);else if(cmd=='i')head=insert(head);else if(cmd=='q')break;elseprintf("请输入正确指令!!");}return 0;}/*删除录入的学生信息中姓名和年龄重复的学生信息*/void delet(struct node *head){struct node *p,*q,*r;p=head->next;while(p!=NULL){q=p;while(q->next!=NULL){r=q->next;if((r->age==p->age)&&strcmp(r->name,p->name)==0){if(r->next!=NULL){q->next=r->next;free(r);}else{q->next=NULL;free(r);}}elseq=r;}p=p->next;}printf("删除成功!");}/*根据用户输入,创建一个长度为n的链表*/struct node *creat(int n){int x,i;char s_name[10];struct node *head,*p,*r;head=(struct node*)malloc(sizeof(struct node));r=head;printf("请输入%d个学生的信息:\n",n);for(i=0;i<n;i++){scanf(" %s",&s_name);scanf("%d",&x);p=(struct node*)malloc(sizeof(struct node)); p->age=x;strcpy(p->name,s_name);r->next=p;r=p;}r->next=NULL;printf("链表已保存!");return(head);}/*对学生信息按年龄从小到大进行排序*/void sort(struct node *head){struct node *p,*q,*small;int temp;char tem[10];for(p=head->next;p->next!=NULL;p=p->next){small=p;for(q=p->next;q!=NULL;q=q->next){if(q->age<small->age)small=q;}if(small!=q){temp=small->age;strcpy(tem,small->name);small->age=p->age;strcpy(small->name,p->name);p->age=temp;strcpy(p->name,tem);}}printf("排序成功!");}/*输出已录入的学生信息*/void output(struct node *head){struct node *pt;pt=head->next;printf("正在打印………\n学生姓名\t\t学生年龄\n");while(pt!=NULL){printf("%-22s  %-10d\n",pt->name,pt->age);pt=pt->next;}}/*在链表的头节点处插入新的节点,即插入一个新的学生信息数据*/struct node * insert(struct node *hed){struct node *new_node;int ag;char nam[10];new_node=(struct node*)malloc(sizeof(struct node));printf("请输入需要添加的学生信息:  ");scanf("%s",&nam);scanf("%d",&ag);strcpy(hed->name,nam);hed->age=ag;new_node->next=hed;printf("插入成功!");return(new_node);}/*按照输入的姓名删除学生信息*/ void delet1(struct node *head) {struct node *p,*r;char sname[10];printf("Please enter student name: ");scanf(" %s",&sname);for(p=head;p->next!=NULL;){r=p;p=p->next;if(strcmp(p->name,sname)==0){r->next=p->next;printf("按名删除已成功!");break;}}}

0 0