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

新手求助:链表问题

44702620 发布于 2008-06-18 02:39, 585 次点击
#include "stdio.h"
#include "iostream.h"
#include "string.h"
struct node
{
    int inum;
    int iscore;
    struct node *nnext;
};
node *create()
{
    int no;
    node *head,*pn,*pt;
    head=0;                           //为什么if中的语句不能放在这里??
    cout<<"产生无序链表:"<<endl;
    cin>>no;
    while(no!=-1)
    {
        pn=new node;
        pn->inum=no;
        cin>>pn->iscore;
        if(head==0)
        {
            head=pn;
            pt=pn;
        }
        else
        {
            pt->nnext=pn;
            pt=pn;
        }
        cin>>no;
    }
    pt->nnext=0;
    return head;
}
void print(node *head)
{
    node *p=head;
    cout<<"输出:"<<endl;
    while(p!=0)
    {
        cout<<p->inum<<'\t'<<p->iscore<<endl;
        p=p->nnext;
    }
}
main()
{
    node *head;
    int no;
    head=create();
    print(head);
}

问题:建立新链表中,循环前就已经将head=0了,那循环中的if(head==0)不是多余的吗,为什么if中的语句不能放在head=0;后面??十分迷茫,
望前辈给予指教!!!
3 回复
#2
447026202008-06-18 18:40
为啥没人回话??知道的麻烦告诉我啊
#3
漫游者李李西2008-06-18 18:53
先回答第一个问题,if()判断主要是将head赋予链表的头结点,第一次进入时,条件满足,可第二次进入循环时head !=0.还有你把if判断放那儿是什么意思啊?
#4
447026202008-06-19 15:12
if语句为何放在那,。这是书上的一个例子,例子上是这样的,我就是搞不明白所以才发贴问的,还有,我试了,if语句中的 head=pn;
            pt=pn;
没法放在第14句head=0后面,否则在运行时,敲入回车键后会出错。。很奇怪!!!
1