#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
typedef struct student
{
int stu_no;
char stu_name[6];
struct student * left;
struct student * right;
}SqList;//定义一个学生信息的结构体,里面有学生的学号,学生的姓名以及两个结构指针
//创建双链表,并把随即取到的学号姓名传入双链表
struct student * Creat_List()
{
printf("...创建双链表...\n");
struct student * last_student,* head;
//创建头节点,并把随即取到的学号、姓名传入头节点
struct student * p;
struct student stu[3];
FILE *fp;
int i = 0;
int j = 0;
int no;//接收文件读出来的数据
char name[6];
fp = fopen("百舸争流.txt","r");//打开文件
if (fp == NULL) //判断是否正常打开文件
{
printf("读取文件失败\n\n");
exit(0);
}
for(int i=0;i<3;i++){
fscanf(fp,"%d %s\n",&no,name);
stu[i].stu_no=no;
strncpy(stu[i].stu_name,name,sizeof(stu[i].stu_name));
}//按照文件里的数据格式 循环的读入每一行的数据,并存入相应的数组缓存中
fclose(fp);
p = (struct student *)malloc(sizeof(struct student));
if(p == NULL)
return 0;
head = p;
head->left = NULL;
head->right = NULL;
head->stu_no = stu[0].stu_no;
strncpy(head->stu_name,stu[0].stu_name,sizeof(head->stu_name)); //将指定长度的字符串复制到字符数组中 */
last_student = head;
for(i = 1;i <3;i++)
{
struct student * new_student[i];
new_student[i] = (struct student *)malloc(sizeof(struct student));
if(new_student[i] == NULL)
return 0;
new_student[i]->stu_no = stu[i].stu_no;
strncpy(new_student[i]->stu_name,stu[i].stu_name,sizeof(new_student[i]->stu_name));
new_student[i]->left = last_student; //左指针指向头结点
new_student[i]->right = NULL; //右指针为空
last_student->right = new_student[i];
last_student = new_student[i]; // 尾指针指向最后
}
return head;
}
//插入节点
struct student * Insert_Node(struct student *p)
{
struct student * new_stu,* head;
int no;
char name[6];
head = p;
new_stu = (struct student *)malloc(sizeof(struct student));
if(new_stu == NULL)
return 0;
if(new_stu->left == NULL)
printf("请输入:学号 姓名");
scanf("%d %s",&no,name);
new_stu->stu_no =no;
strncpy(new_stu->stu_name,name,sizeof(new_stu->stu_name));
head->left = new_stu;
new_stu->left = NULL;
new_stu->right = head;
head = new_stu;
return new_stu;
}
//遍历链表
int Show_List(struct student * p)
{
printf("...遍历...\n");
struct student * temp;
temp = p;
while(temp != NULL)
{
printf("%d %s\n",temp->stu_no,temp->stu_name);
temp = temp->right;
}
return 0;
}
//对双链表里面的数据按照学生的学号进行从小到大的排序:
int Bubble_Sort(struct student * p)
{
struct student * temp;
struct student *q,*a;
a = p;
int exchange = 0;
for(q = p;q != NULL;q = q->right)
{
for(temp = p; temp != NULL; temp = temp->right)
{
if(temp->stu_no > temp->right->stu_no)
{
exchange = temp->stu_no;
temp->stu_no = temp->right->stu_no;
temp->right->stu_no = exchange;
}
}
}
while(a != NULL)
{
printf("排序后的学号为:%d\n",a->stu_no);
printf("排序后的姓名为:%s\n",a->stu_name);
a = a->right;
}
return 0;
}
int main()
{
static struct student * p;
p = Creat_List();
Show_List(p);
Bubble_Sort(p);
return 0;
}
复习C语言双向链表的使用
最新推荐文章于 2024-05-01 16:12:25 发布