# 双向链表的c语言实现

2 篇文章 0 订阅

## 双向链表的c语言实现

### 代码实现

#### 问题描述

Write a program to print students’ information (ID number, name, gender, and scores) by the order of their scores.

#### 实际代码（前部分）

##### 头文件和预处理部分
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXID 1
#define MAXNAME 15

##### 结构体定义
typedef struct student
{
int ID[MAXID];
char name[MAXNAME];
int gender;     /* 0 for boy, 1 for girl */
float score;
struct student *next;
struct student *last;
} INF;


##### 声明部分
void getinf(INF *p);
void add(INF *p);
void insert_sort(INF *p);
void freeall(INF *p);       /* find the last, free from the last to the first */
void print(INF *p);
void swap(INF *, INF *);


##### main部分
int main()
{
printf("ID\tname\tgender\tscore\n");
INF *start = (INF *)malloc(sizeof(INF));
start->last = start->next = NULL;
INF *p = start;
getinf(p);
int i = 0;
while (i++ < 3)
{
add(p);
p = p->next;
if (!p)
{
printf("add error\n");
return 1;
}
getinf(p);
}
p = start;
insert_sort(p);
for (; p; p = p->next)
print(p);
p = start;
freeall(p);
}


##### 函数部分的部分
###### insert_sort
void insert_sort(INF *p)
{
INF *start, *search;
for (start = p->next; start->next; start = start->next)
{
for (search = start; search - p; search = search->last)
{
if (search->score > search->last->score)
{
swap(search, search->last);
}
}
}           /* lose a time */
for (search = start; search - p; search = search->last)
{
if (search->score > search->last->score)
{
swap(search, search->last);
}
}
}

###### swap

void swap(INF *first, INF *second)
{
int tempID[MAXID];
for (int i = 0; i < MAXID; ++i)
tempID[i] = (first->ID)[i];
for (int i = 0; i < MAXID; ++i)
(first->ID)[i] = (second->ID)[i];
for (int i = 0; i < MAXID; ++i)
(second->ID)[i] = tempID[i];
char ctemp[MAXNAME];
strcpy(ctemp, first->name);
strcpy(first->name, second->name);
strcpy(second->name, ctemp);
int itemp;
itemp = first->gender;
first->gender = second->gender;
second->gender = itemp;
float ftemp;
ftemp = first->score;
first->score = second->score;
second->score = ftemp;
}


## 程序 = 数据结构 + 算法

• 2
点赞
• 1
收藏
觉得还不错? 一键收藏
• 打赏
• 0
评论
12-13
10-01 1253
08-18 2095
09-12 1590
10-16 8024
09-03
05-13
07-31
07-05
06-03
05-02
11-27 1247
04-21 744

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

¥1 ¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。