C语言-链表


链表

案例:当有很多结构对象时,我们可以选择用数组来存储 ,可以用数组存储结构指针,在一定程度上减小了内存浪费;再进一步可以用链表来完成

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include "stdio.h"
#include "stdlib.h"
#include "conio.h"
#include "string.h"
#define MAXLEN 12

struct book{
char title[40];
char author[20];
int price;
};

main(){
int i;
struct book * library[MAXLEN];
for(i=0; i<MAXLEN; i++){
library[i] = (struct book *) malloc (sizeof (struct book));
}
}

创建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
#define TSIZE 30
struct film{
char title[40];
int rating;
struct film * next;
};

main(){
// 输入创建链表
puts("enter movie title: ");
struct film * current, *head, *prev;
char input[TSIZE];
head = NULL;
while(gets(input) != NULL && input[0] != '\0'){
current = (struct film *) malloc (sizeof(struct film));
if(head==NULL)
head = current;
else
prev -> next = current;
current -> next = NULL;
strcpy(current->title, input);
puts("Enter your rating <0-10>: ");
scanf("%d", &current->rating);
// / scanf不会自动清除输入缓冲区的换行符
while(getchar()!='\n')
continue;
puts("Enter next moive title(empty line to stop): ");
prev = current;

}

// 显示链表
if(head!=NULL){
printf("Here is the movie list: \n");
}else{
printf("No data Entered.\n");
}
current = head;
while(current!=NULL){
printf("moive: %s Rating: %d\n", current->title, current->rating);
current= current->next;
}
// 任务完成,释放分配空间
current = head;
while(current!=NULL){
free(current);
current = current->next;
}
printf("Bye\n");
}

显示

1
2
3
4
5
6
7
8
9
10
if(head!=NULL){
printf("Here is the movie list: \n");
}else{
printf("No data Entered.\n");
}
current = head;
while(current!=NULL){
printf("moive: %s Rating: %d\n", current->title, current->rating);
current= current->next;
}

释放内存

1
2
3
4
5
current = head;
while(current!=NULL){
free(current);
current = current->next;
}

本文标题:C语言-链表

文章作者:TTYONG

发布时间:2020年08月28日 - 12:08

最后更新:2020年09月10日 - 17:09

原始链接:http://tianyong.fun/C%E8%AF%AD%E8%A8%80-%E9%93%BE%E8%A1%A8.html

许可协议: 转载请保留原文链接及作者。

多少都是爱
0%