刚学会单链表,于是就来写一个巩固一下哈哈哈
之前因为动态内存分配没有理解到位所以卡了很久
这里的data只有姓名和学号(因为懒)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct student{
char name[10];
int num;
struct student *next;
};
struct student *createList(){
struct student *headnode = (struct student *)malloc(sizeof(struct student));
strcpy(headnode->name," ");
headnode->next = NULL;
headnode->num = 0;
return headnode;
}
struct student *createnode(char name[10],int num){
struct student *newnode = (struct student *)malloc(sizeof(struct student));
strcpy(newnode->name, name);
newnode->num = num;
newnode->next = NULL;
return newnode;
}
void insertnode(struct student *headnode,char name[10],int num){
struct student *node = createnode(name,num);
while(headnode->next){
headnode = headnode->next;
}
headnode->next = node;
node->next = NULL;
}
void printlist(struct student *headnode){
struct student *p = headnode->next;
if(p==NULL){
printf("the list is empty,please choose the option 2 to add something\n");
}
while (p)
{
printf("num: %d name: %s\n", p->num,p->name);
p = p->next;
}
}
void delete(struct student *headnode,int n){
struct student *p = headnode->next;
struct student *fp = headnode;
while(p&&p->num!=n){
p = p->next;
fp = fp->next;
}
if(p==NULL){
printf("the number is invalid\n");
}else{
fp->next = fp->next->next;
free(p);
printf("you have just delete the data!\n");
}
}
void searchdata(struct student *headnode,int search){
struct student *p = headnode->next;
while(p){
if(p->num==search){
printf("num: %d name: %s\n", p->num,p->name);
break;
}else{
p = p->next;
}
}
if(p==NULL){
printf("the number is invalid\n");
}
}
void changename(struct student *headnode,int num,char new_name[10]){
struct student *p = headnode->next;
while(p){
if(p->num==num){
strcpy(p->name, new_name);
break;
}else{
p = p->next;
}
}
if(p==NULL){
printf("the number is invalid\n");
}
}
int main(){
char name[10],new_name[10];
int course, num, n,search;
struct student *list = createList();
printf("\n\n\t\tWELCOMT TO THE LINKEDLIST OPERATION\n");
do{
printf("\nplease choose your operation: 1.search list 2.insert data 3.printf list 4.delete 5.change 6.quit\n (input the number): ");
scanf("%d", &course);
switch (course)
{
case 1:
printf("please input the num that you want to search: ");
scanf("%d", &search);
searchdata(list, search);
break;
case 2:
printf("please input the num: ");
scanf("%d", &num);
printf("please input the name: ");
scanf("%s", name);
insertnode(list, name,num);
break;
case 3:
printlist(list);
break;
case 4:
printf("please input the number which you want to delete:");
scanf("%d", &n);
delete (list, n);
break;
case 5:
printf("please input the number which you want to change the name:");
scanf("%d", &num);
printf("please input the newname: ");
scanf("%s", new_name);
changename(list, num, new_name);
break;
case 6:
printf("you have quit the program!");
return 0;
}
} while (1);
return 0;
}