注册 登录
编程论坛 C++教室

求助一简单链表问题

hxxgy 发布于 2009-11-17 15:48, 421 次点击
我写的这个代码的ShowLink函数有问题,但是就是不知道怎么改。不运行show函数的时候程序还能正常运行,只要一运行就有问题。

#include <iostream.h>


struct Node
{
    int i;
    Node *pt;
};

Node *head = NULL;

int n;               //记录节点个数

Node* CreatLink()
{
    Node *p, *next;
    p = next = new Node;
   
    cout<<"value"<<endl;
    cin>>p->i;
   
    if (head = NULL)
    {
        head = p;
    }
    else
    {
        while ( p->i )
        {
            next = new Node;
            cout<<"value"<<endl;
            cin>>next->i;
        
            p->pt = next;
            p = next;
            n++;
        }
        
    }
    p->pt = NULL;
    return head;

}

void ShowLink (Node *ptp)
{

    while (ptp->pt)
    {
        cout<<n<<endl;
        cout<<ptp->i<<endl;
        ptp=ptp->pt;
    }
}

void main ()
{
    CreatLink();
    ShowLink(CreatLink());
   
    cout<<n<<endl;

}
5 回复
#2
flyingcloude2009-11-17 22:07
程序代码:
Node* CreatLink()
{
    Node *p, *next;
    p = next = new Node;
 
    cout<<"value"<<endl;
    cin>>p->i;
 
    if (head == NULL) //小心些,或者以后可以写成if(NULL == head),这样就不会出现if(NULL = head)的问题了
    {
        head = p;
    }
    else
    {
        while ( p->i )
        {
            next = new Node;
            cout<<"value"<<endl;
            cin>>next->i;
      
            p->pt = next;
            p = next;
            n++;
        }
      
    }
    p->pt = NULL;
    return head;
}

#3
hxxgy2009-11-18 13:43
谢谢。晕,这种小错误,真是一不小心就会犯了。
#4
hxxgy2009-11-18 13:46
不过貌似现在没错误了,但是我的show函数仍然没工作,就是我输入完毕后,他不显示我的链表节点。这是怎么回事?
#5
逆光2009-11-18 19:32
貌似将以下代码删除能正确计算结点个数
   
    //cout<<"value"<<endl;
    //cin>>p->i;
   
 不删则输入1,2,3,0显示为2

不知道对不对,至于原因还请各位大大指点一二   
#6
逆光2009-11-18 20:04
这样好像是对的

#include <iostream.h>


struct Node
{
    int i;
    Node *pt;
};

Node *head = NULL;

int n=1;               //记录节点个数

Node* CreatLink()
{
    Node *p;
    p  = new Node();
   
    cout<<"value"<<endl;
    cin>>p->i;
   
    if (head == NULL)
    {
        head = p;
    }
    else
    {
        while ( p->i )
        {   
            
            cout<<"value"<<endl;
            cin>>p->i;
        
            p->pt = p;
            
            ++n;
        }
        n++;
        
    }
    p->pt = NULL;
    return head;

}

void ShowLink (Node *ptp)
{

    while (ptp->pt)
    {
        cout<<n<<endl;
        cout<<ptp->i<<endl;
        ptp=ptp->pt;
    }
}

void main ()
{
    CreatLink();
    ShowLink(CreatLink());
   
    cout<<n<<endl;

}

1