[問題] 關於linklist跟struct的問題

看板C_and_CPP (C/C++)作者 (小馬非馬)時間16年前 (2009/04/28 20:13), 編輯推噓5(507)
留言12則, 6人參與, 最新討論串1/3 (看更多)
#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

04/28 20:22, , 1F
1. 不管是什麼型別的"指標" 所花費的空間都是一定的
04/28 20:22, 1F

04/28 20:28, , 2F
2. 你改出來的 plast 在出回圈時是 NULL, 又被設成 pnode
04/28 20:28, 2F

04/28 20:28, , 3F
跟他要把 plast 的 pnext 連到頭去的用意完全不同
04/28 20:28, 3F

04/28 20:41, , 4F
2.我懂了,那1.中node寫的用意是什麼?
04/28 20:41, 4F

04/28 21:06, , 5F
因為c++為你做了 typedef struct{...} node;
04/28 21:06, 5F

04/28 21:57, , 6F
對了, (*pnode).xxxx 可以直接用 pnode->xxxx 就行了:)
04/28 21:57, 6F

04/28 22:51, , 7F
嗯,只是剛開始寫我覺得用指標比較促進思考XD謝謝大家~
04/28 22:51, 7F

04/28 23:20, , 8F
你的 insert() 中有 memory leak
04/28 23:20, 8F

04/28 23:38, , 9F
如果是放 struct node { node x; }; 就不行, 如你所說, 不
04/28 23:38, 9F

04/28 23:38, , 10F
知道要放多少空間, 但是 struct node { node *p;}; 的時候
04/28 23:38, 10F

04/28 23:39, , 11F
無論 struct node 長啥樣, node *p; 都是固定大小
04/28 23:39, 11F

04/28 23:39, , 12F
所以可以允許這麼用
04/28 23:39, 12F
文章代碼(AID): #19zlBhsP (C_and_CPP)
文章代碼(AID): #19zlBhsP (C_and_CPP)