链表是C中高级数据的表示形式之一,它不像数组那样必须在程序运行之前就定义好数组的长度,而是让程序在运行时可以随时申请内存空间进行数据的存储和运算,从而增加了程序的灵活性。<p>下面记录了我在学习C语言过程中的一段有关链表的实例,内容相对易懂,现在拿出了与大家分享。</p><p>
</p><p>程序的目的是:构建一个有电影名称和评分的链表,并将链表列出。</p><p>
</p><p>代码如下:</p>
/*
film.c使用结构链表
*/
#include <stdio.h>
#include <stdilb.h>//使用malloc()
#include <string.h>//使用strcop()
#define TSIZE 45
struct film
{
char title [TSIZE];//电影名
int rating;//电影评分
struct film *next;//指向链表的下一个结构
};
int main (void)
{
struct film *head =NULL;//头指针
struct film *prev,*current;//指向前一个节点的指针;指向当前节点的指针。
char input[TSIZE];//存放片名的数组
//收集并存储信息
puts("Enter first moive title:")
while (gets(input) != NULL && input[0] !='\0' )
{
current = (struct film*) malloc(sizeof (struct film));
if (head == NULL)//第一个结构
head == current; //记录头指针
else// 其他的结构
pre -> next = current;
current -> next = NULL;
strcpy (current -> title ,input);//存储影片名称
puts("Enter your rating <0 - 10>:");
scanf("%d",& (current -> rating));//存储影片评分
while(getchar() != '\n')
continue;
puts("Enter next moive title (empty line to stop):");
prev = current;
}
//打印电影列表
if (head == NULL)
pritnf("NO data entered:");
else
printf("Here is the moive list:");
current = head;//将当前操作的指针设置为头指针,准备打印电影列表
while(current != NULL)
{
printf("Movies: %s Rating: %d\n",current -> title, current -> rating);
current = current -> next;//指针指向下一个
}
//打印完成,释放所分配的内存
current = head;
while (current != NULL)
{
free(current);
current = current -> next;
}
printf ("Print is OK, Bye");
return 0;
}
总结:
显示列表的方法是开始时把一个指针(current)设置为指向第一个结构。至于为什么不使用head来遍历整个列表,而是创建一个新指针current,是因为使用head会改变head的值,这样程序就不能再次找到列表的开始处。
创建列表分为三个步骤:
1.使用malloc()函数为一个结构分配足够的空间;
2.存储这个结构的地址;
3.把正确的信息复制到这个结构中。