0
点赞
收藏
分享

微信扫一扫

我的第一个链表

mm_tang 2022-03-17 阅读 112
#include <stdio.h>
#include<windows.h>
#include <stdlib.h>
struct student
{
char name[20];
int num;
int age;
};
struct Node
{
struct student data;
struct Node* next;
};
struct Node* creatlist() //创建链表表头
{
struct Node* headNode=(struct Node*)malloc(sizeof(struct Node)); //申请内存
//headNode->data=1;
headNode->next=NULL; //指针初始化
return headNode;
};
struct Node* creatNode(struct student data) //创立新的节点
{
struct Node* newNode=(struct Node*)malloc(sizeof(struct Node));
newNode->data=data;
newNode->next=NULL;
return newNode;
}
void printlist(struct Node*headNode) //打印链表内容
{
struct Node*pmove=headNode->next;
printf("姓名\t语文\t数学\n");
while(pmove)
{
printf("%s\t%d\t%d\n",pmove->data.name,pmove->data.num,pmove->data.age);
pmove=pmove->next;
}
}
void insert(struct Node*headNode,struct student data) //头部插入
{
struct Node* newNode=creatNode(data);
newNode->next=headNode->next;
headNode->next=newNode;
}
/*
void insert(struct Node* headNode,struct stuednt data)
{
struct Node* newNode=creatNode(data);
newNode->next=headNode->next;
headNode->next=newNode;
*/

void insertbypos(struct Node*headNode,struct student data,int posdata) //指定位置插入
{
struct Node* posNode=headNode->next;
struct Node* preposNode=headNode;
while(posNode->data.num!=posdata)
{
preposNode=posNode;
posNode=preposNode->next;
if(posNode == NULL)
{
return;

}
}
struct Node* newNode=creatNode(data);
newNode->next=posNode->next;
posNode->next=newNode;
}
void insertbytail(struct Node* headNode,struct student data) //尾部插入
{
struct Node* newNode=creatNode(data);
struct Node* tail=headNode;
while(tail->next!=NULL)
{
tail=tail->next;
}
tail->next=newNode;
}
void delet(struct Node* headNode,int posdata) //指定位置删除数据
{
struct Node* posNode=headNode->next;
struct Node* preposNode=headNode;
while(posNode->data.num!=posdata)
{
preposNode=posNode;
posNode=preposNode->next;
if(posNode == NULL)
{
return;

}
}
preposNode->next=posNode->next;
free(posNode);
}
int main()
{
struct Node* list=creatlist();
struct student info;
int n;
printf("请输入学生个数:");
scanf("%d",
while(n--)
{
printf("依次输入学生姓名,语文成绩,数学成绩\n");
scanf("%s%d%d",info.name,&info.num,
insert(list,info);
}
//Sleep(2000);
printlist(list);
return 0;
}
举报

相关推荐

0 条评论