【關于鏈表】
建立一個結構數組,包含電影名稱和評分,可以不斷添加,對此我們可以建立以下結構
#define SIZE 45
struct film{
char title[SIZE];
int rating;
struct film * next; //尾指針,為了表明結構后面沒有其他結構,將next成員指針設置為NULL(空指針)
}
struct film * head; //頭指針,,指向鏈表中的第一項,主要用于存儲第一個結構的地址
這時候,在用戶輸入第二部電影的信息時,程序為第二個film類型結構分配空間,把新的結構地址存儲在第一個結構的next成員中(擦寫了之前存儲在改成員中的NULL),這樣鏈表第一個結構中的next指針指向第二個結構,將第二個結構中的next成員設置為空指針,這樣就完成了一個鏈表的構造。
【創建鏈表】
創建鏈表設計以下三步
1、使用malloc()函數為結構分配足夠的空間
2、存儲結構的地址
3、把當前信息拷貝到結構中
【顯示鏈表】--->【釋放鏈表】
在鏈表中,每一個鏈接點叫做節點(node),因此,我們把node作為節點結構的標記。
書中的例程中關于內存的釋放是錯誤的,錯誤代碼示例:
/* 依次釋放指針內存 */
current = head;
while (current != NULL)
{
free(current);
head = current->next;
}
在這段代碼中,首先將head賦給current,但是在后面的while循環中,直接釋放了current的內存,
那么就無法實現current->next。
更正后的代碼如下:
/* 依次釋放指針內存 */
current = head;
while (current != NULL)
{
prev = current->next;
free(current);
current = prev;
}
更正后,將指針內存的依次釋放
程序示例
/* films.c -- 使用結構鏈表 */
#include<stdio.h>
#include<stdlib.h> //提供malloc()函數
#include<string.h> //提供strcpy函數
#define TSIZE 45
struct film {
char title[TSIZE];
int rating;
struct film * next;
};
char * s_gets(char *st, int n);
int main()
{
struct film *head = NULL;
struct film *current; //當前
struct film *prev; //下一個
char input[TSIZE];
/* 收集并存儲信息 */
puts("enter first movie title:");
while (s_gets(input, TSIZE) != NULL&&input[0] != '\0')
{
/* 初始化一個結構 */
/* current是結構的首地址、指向film結構的指針 */
current = (struct film *)malloc(sizeof(struct film));
if (head == NULL)
head = current;
else
prev->next = current;
current->next = NULL;
strcpy(current->title, input);
printf("enter your rating <0-10>:");
scanf("%d", ¤t->rating);
while (getchar() != '\n')
continue; //吃掉換行符
puts("enter next movie title (empty line to stop):");
prev = current; //再次初始化一個結構,循環
}
/* 顯示鏈表 */
if (head == NULL)
printf("no data entered.");
else
printf("here is the movie list:\n");
/* 遍歷鏈表時,創建一個新的指針,是為了保護head的值,防止其改變*/
/*否則程序就找不到鏈表的開始處*/
current = head;
while (current != NULL)
{
printf("movie: %s rating: %d\n", current->title, current->rating);
current = current->next;
}
/* 依次釋放指針內存 */
current = head;
while (current != NULL)
{
prev = current->next;
free(current);
current = prev;
}
printf("bye!\n");
return 0;
}
char *s_gets(char *st, int n)
{
char *ret_val;
char *find;
ret_val = fgets(st, n, stdin);
if (ret_val)
{
find = strchr(st, '\n');
if (find)
*find = '\0';
else
while (getchar() != '\n')
continue;
}
return ret_val;
}