作者conan77420 (小马非马)
看板C_and_CPP
标题[问题] 关於linklist跟struct的问题
时间Tue Apr 28 20:13:27 2009
#include<iostream>
using std::cout;
using std::cin;
using std::endl;
struct node
{
int data;
node *pnext;
};
//=================以上为struct==============
int data=0;
node *phead=0;
int count=0;
//================linklist资料差入===========
int insert(int data)
{
node *pnode=new node;
(*pnode).data=data;
(*pnode).pnext=0;
if(phead==0)
{phead=pnode;}
else
{ node *plast=new node;
plast=phead;
while((*plast).pnext!=0)
{plast=(*plast).pnext;}
(*plast).pnext=pnode;
}
}
//============================================
//==============将linklist中的值分别印出======
void print()
{
node *pnode=new node;
pnode=phead;
while(pnode!=0)
{
cout<<"Link list datais:"<<(*pnode).data<<endl;
pnode=(*pnode).pnext;
}
}
//============================================
int main()
{
while(1)
{
if(count==5)
{
print();
count=0;
}
cout<<"Enter data: ";
cin>>data;
insert(data);
count++;
}
system("pause");
}
//=======================================
小弟算是第一次碰linklist,
程式打一打也总算有对应的结果〈还没用dalete〉
想请教的是:
1.在struct中定义的data宣告成int形式没问题
,但为什麽在宣告指标时可以用不是保留字的
node来写?这样电脑怎麽知道要借多少记忆
体大小给我们呢?
2.在insert副程式中,为什麽不能将最後的
while((*plast).pnext!=0)
{plast=(*plast).pnext;}
(*plast).pnext=pnode;
改成
while(plast!=0)
{plast=(*plast).pnext;}
plast=pnode;
其实好像怪怪的,但我自己无法解释,请教各位
谢谢!
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 61.229.137.204
1F:→ james732:1. 不管是什麽型别的"指标" 所花费的空间都是一定的 04/28 20:22
2F:推 ledia:2. 你改出来的 plast 在出回圈时是 NULL, 又被设成 pnode 04/28 20:28
3F:→ ledia: 跟他要把 plast 的 pnext 连到头去的用意完全不同 04/28 20:28
4F:→ conan77420:2.我懂了,那1.中node写的用意是什麽? 04/28 20:41
5F:推 snowlike:因为c++为你做了 typedef struct{...} node; 04/28 21:06
6F:推 VictorTom:对了, (*pnode).xxxx 可以直接用 pnode->xxxx 就行了:) 04/28 21:57
7F:→ conan77420:嗯,只是刚开始写我觉得用指标比较促进思考XD谢谢大家~ 04/28 22:51
8F:推 littleshan:你的 insert() 中有 memory leak 04/28 23:20
9F:推 ledia:如果是放 struct node { node x; }; 就不行, 如你所说, 不 04/28 23:38
10F:→ ledia:知道要放多少空间, 但是 struct node { node *p;}; 的时候 04/28 23:38
11F:→ ledia:无论 struct node 长啥样, node *p; 都是固定大小 04/28 23:39
12F:→ ledia:所以可以允许这麽用 04/28 23:39