1. 程式人生 > >動態連結串列的建立—尾插法

動態連結串列的建立—尾插法

今天嘗試了簡單動態連結串列的建立  不幸的是失敗了  目前還沒有找出錯在哪兒  明天一定要搞清楚錯誤的原因  到時在對本文進行修改

#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、注意:需要一個頭結點來標明連結串列的初始位置,否則連結串列資料沒辦法輸出