您的位置:首页 > 其它

链表(一) 单向链表

2015-10-22 19:17 274 查看
单向链表:



见 书 C primer plus (488 程序 17.2)

#include <stdio.h>
#include <stdlib.h>      /* has the malloc prototype      */
#include <string.h>      /* has the strcpy prototype      */
#define TSIZE    45      /* size of array to hold title   */

struct film {
char title[TSIZE];    // 书名
int rating;           // 评分
struct film * next;  // 指向链表的下一个结构
};

int main(void)
{
struct film * head = NULL;                // 头指针
struct film * prev, * current;            // 前指针   当前指针
char input[TSIZE];

/* Gather  and store information          */  //收集并保存信息
puts("Enter first movie title:");

while (gets(input) != NULL && input[0] != '\0')          // input  0x12ff44 存放书名 great expections
{
current = (struct film *) malloc(sizeof(struct film));       //  ¤t=0x0012ff74   current=0x00431d70       第二次 current=0x431d00
if (head == NULL)       /* first structure       */
head = current;                                 //  把 current 指向的地址 传给 head指针,那么 head=0x00431d70
else                    /* subsequent structures */
prev->next = current;                                                                                     //   prev->next=0x431d00

current->next = NULL;                         //  表示当前结构是列表中的最后一个
strcpy(current->title, input);               //  ¤t->title=0x00431d70  "great exception "   current->title= 0x00431d70
puts("Enter your rating <0-10>:");

scanf("%d", ¤t->rating);               // ¤t->rating=0x00431da0  "8"          current->rating=  8

while(getchar() != '\n')
continue;
puts("Enter next movie title (empty line to stop):");
prev = current;                           // &prev = 0x0012ff78  prev=0x00431d70

}

/* Show list of movies                    */
if (head == NULL)
printf("No data entered. ");
else
printf ("Here is the movie list:\n");

current = head;                   // ¤t=0x0012ff74  current=0x00431d70   也就是 开始
while (current != NULL)
{
printf("Movie: %s  Rating: %d\n",
current->title, current->rating);
current = current->next;      // 指向下一个指针
}

current=head;                    // 从开头指针 开始释放。
while(current != NULL)
{
free(current);
current=current->next;

}
printf("Bye !\n");

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: