动态链表的建立—尾插法

来源:互联网 发布:男模项海 知乎 编辑:程序博客网 时间:2024/03/29 23:58

今天尝试了简单动态链表的建立  不幸的是失败了  目前还没有找出错在哪儿  明天一定要搞清楚错误的原因  到时在对本文进行修改

#include <iostream>
using namespace std;
struct node
{
int num;
struct node *next;
};
void  main()
{
  int i,num;
  struct node *head;
  struct node *p,*q;
  head=NULL;
  p=q=(struct node *)malloc(sizeof(struct node));
  while (head==NULL)                            //错误一 ,这里的head空间没有得到申请
  {
  head=p;
  }
  for(i=0;i<5;i++)
  {
p=(struct node *)malloc(sizeof(struct node));
scanf("%d",&num);
p->num=num;
q=p; //这里是一个死循环,p和q共有同一个内存地址,在下一步的操作中又不断将自己指向自己,构成的是一个死循环
p=q->next;
  }
  p->next=NULL;
  q=head;
  while(q->next!=NULL)
  {
printf("%d ",num);                                            //这里的num应该由p->num来输出,而且head中是没有数据的,不能输出
q=q->next;
  }
  free(q);
}

今天完成了修改,错误已经在上面的程序中指出  以下是修改好的程序  这里写的是链表的尾插法

下篇文章中将介绍链表的头插法

正确的程序应该是这样的

#include <stdio.h>
#include <stdlib.h>
struct node
{
int num;
struct node *next;
};
void  main()
{
  int i,num;
  struct node *head;
  struct node *p,*q;
  head=p=q=(struct node *)malloc(sizeof(struct node));
  head->next=NULL;
  while (head->next==NULL)
  {
head->next=q;
  }
  for(i=0;i<5;i++)
  {
p=(struct node *)malloc(sizeof(struct node));
scanf("%d",&num);
p->num=num;
q->next=p;
q=p;
  }
q->next=NULL;
q=head->next;
while(q!=NULL)
{
printf("%d ",q->num);
q=q->next;
}
free(q);
}


总结:这是一个简单的尾插法动态链表

1、用p建立一个节点,让q来指向它,再将p移动到q节点的位置,继续输入数据,重复操作,就可以完成动态链表的建立;

2、注意:需要一个头结点来标明链表的初始位置,否则链表数据没办法输出