链表的定义
链表是物理存储单元上的非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针连接次序实现的。链表中每一个元素成为节点。链表有一系列节点组成,节点可以在运行状态下生成。每个节点包括两个部分:一个是存储数据元素的数数据域,另一个是存储下一个节点地址的指针域。
定义节点类型
typedef struct node
{
int data;/*数据域*/
struct node *next; /*指针域*/
}Node;
附加头节点数据域为空
指针每一次指向 next ,程序输出 data;直至next 为NULL 为止;
#include "stdio.h"
#include "malloc.h"
typedef struct node
{
int data;
struct node *next;
}Node;
void create(Node *head)
{
Node *p;
int x;
while(1)
{
printf("请输入一个整数(退出请输入0)");
scanf("%d",&x);
if(x==0)
break;
p=(Node *)malloc(sizeof(Node));
p->data=x;
//插入
p->next=head->next;
head->next=p;
}//end of while
}
void output(Node *h)
{
Node *p;
if(h->next==NULL)
{
printf("链表为空\n");
return;
}
printf("链表的元素为:");
p=h->next;
while(p!=NULL)
{
printf("%d",p->data);
p=p->next;
}
printf("\n");
}
void term(Node *h)
{
Node *p,*q;
p=h;
while(p!=NULL)
{
q=p->next;
free(p);
p=q;
}
}
int main()
{
Node *head;
//生成带附加头结点的空链表
head=(Node *)malloc(sizeof(Node));
if(head==NULL)
return 0;
head->next=NULL;
create(head);//建立有数据的链表
output(head);//输出链表
term(head); //释放链表的内存空间
}