標(biāo)題: 單鏈表小test遇到的問題 [打印本頁]

作者: liuyang    時(shí)間: 2012-1-14 03:46
標(biāo)題: 單鏈表小test遇到的問題
   看了數(shù)據(jù)結(jié)構(gòu)前幾篇按自己思路 寫了個(gè)單鏈表的test ,   主要是創(chuàng)建和查找的測試。

#include<stdio.h>
#include<malloc.h>

struct list1{
 int wdata;
 struct list1 *node;   //指向下一個(gè)連表
};

void create_l(struct list1 &LL,int n)   //創(chuàng)建鏈表
{
    struct list1 *p,*q;
    int i;
 p=(struct list1 *)malloc(sizeof(struct list1));
 LL=*p;
 for(i=0;i<n;++i)
 {
      q=(struct list1 *)malloc(sizeof(struct list1));
   scanf("%d",&q->wdata);
   p->node=q;  前個(gè)鏈表元素的指針域?yàn)檫@個(gè)鏈表元素
   p=q;     //這個(gè)鏈表元素作為下個(gè)鏈表元素的前一個(gè)鏈表
 }
 p->node=NULL;
}

struct list1* fdata(struct list1 *b,int aa)   //查找數(shù)據(jù)
{
   while((b!=NULL)&&(b->wdata!=aa))
     b=b->node;
   return b;
}
int main()
{
 struct list1 cl;
 struct list1* cll;
  create_l(cl,5);
  cll=fdata(&cl,3);
  if (cll==NULL)
  {
   printf("NO");
  }else{
   printf("find");
  }
 return 0;
}

 

   我跑了下VC拋出了異常,于是我打斷點(diǎn)看了下發(fā)現(xiàn)  fdata()中的b鏈表沒有得到想要的,于是查看create_l()創(chuàng)建鏈表的函數(shù),

我看了半天沒有發(fā)現(xiàn)邏輯上的問題,于是單步調(diào)試,發(fā)現(xiàn)LL的沒有指針域沒有賦值但是p明明賦了值,甚是奇怪,于是我查看了下 *p與LL看他們原始的內(nèi)容,發(fā)現(xiàn)一致。于是我感到很納悶,于是又想到看看他們p與&LL的指針的值,發(fā)現(xiàn)不一樣。突然才恍然大悟。

 原來我 只是把p指向的stuct list1的內(nèi)存拷貝了賦給LL,在后面的操作都是在p指向的內(nèi)存中作操作,和LL的內(nèi)存沒有任何關(guān)系。 這個(gè)錯(cuò)誤對(duì)于我新手來說,還真容易犯啊。

 

void create_l(struct list1 &LL,int n)   //創(chuàng)建鏈表
{
    struct list1 *p,*q,*cl;
    int i;
 p=(struct list1 *)malloc(sizeof(struct list1));
 cl=p;     //把鏈表頭地址指針存放起來
 for(i=0;i<n;++i)
 {
      q=(struct list1 *)malloc(sizeof(struct list1));
   scanf("%d",&q->wdata);
   p->node=q;
   p=q;
 }
 p->node=NULL;
 LL=*cl;    //把鏈表頭地址的內(nèi)容拷貝賦給LL,這樣下個(gè)鏈表元素的指針也copy 過來了。 
}

 

 寫雙鏈表的時(shí)候才發(fā)現(xiàn)這個(gè)創(chuàng)建其實(shí)是有問題的,代碼寫多了。改為

 

void create_l(struct list1 &LL)   //創(chuàng)建鏈表
{
    struct list1 *p,*q;
    int a;

    p=&LL;

  scanf("%d",&a);

while(a!=-1)      //輸入-1為結(jié)束

{
      q=(struct list1 *)malloc(sizeof(struct list1));
   scanf("%d",&q->wdata);
   p->node=q;  前個(gè)鏈表元素的指針域?yàn)檫@個(gè)鏈表元素
   p=q;     //這個(gè)鏈表元素作為下個(gè)鏈表元素的前一個(gè)鏈表

}
 p->node=NULL;
}

 

這樣才是正確的,呵呵,果然新手一開始什么問題都怪怪的。





歡迎光臨 (http://www.torrancerestoration.com/bbs/) Powered by Discuz! X3.1