建立线性链表的过程

来源:互联网 发布:mac退出u盘 快捷键 编辑:程序博客网 时间:2024/05/09 20:21

1.定义链表的节点,可以将节点定义为结构体,因为链表的节点包含数据以及指向节点的指针,如下:

struct node
{
 int d;
 struct node *next;
};

2.定义一个head节点作为链表的头结点,定义一个指向这种节点的指针*p用于创建新的节点的地址分配,*q用于指向当前链表最后一个节点,如下:

 struct node *head,*p,*q;
 head=NULL;
 q=NULL;
 scanf("%d",&x);
 while(x>0)
 {
  p=(struct node*)malloc(sizeof(struct node));
  p->d=x;
  p->next=NULL;
  if(head==NULL)
  head=p;
  else
     q->next=p;
     q=p;
     scanf("%d",&x);
 }
 p=head;

3.从head节点开始打印节点中的数据,并释放节点所占的内容,直到将最后一个节点打印完毕,如下:

while(p!=NULL)
 {
  printf("%d\n",p->d);
  q=p;
  p=p->next;
  free(q);
 }

 

 

整体的小程序:

#include
#include

struct node
{
 int d;
 struct node *next;
};

void main()
  int x;
 struct node *head,*p,*q;
 head=NULL;
 q=NULL;
 scanf("%d",&x);
 while(x>0)
 {
  p=(struct node*)malloc(sizeof(struct node));
  p->d=x;
  p->next=NULL;
  if(head==NULL)
  head=p;
  else
     q->next=p;
     q=p;
     scanf("%d",&x);
 }
 p=head;
 while(p!=NULL)
 {
  printf("%d\n",p->d);
  q=p;
  p=p->next;
  free(q);
 }
}

0 0