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

看板C_and_CPP (C/C++)作者 (小馬非馬)時間16年前 (2009/04/29 21:27), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串2/3 (看更多)
※ 引述《conan77420 (小馬非馬)》之銘言: 這次我多加入delete的功能,程式如下 : #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; : } : } //============================================ void del() { node *pnode=new node; pnode=phead; node *temp=0; while(pnode!=0) { temp=(*pnode).pnext; delete pnode; pnode=temp; } } //============================================== : int main() : { : while(1) : { : if(count==5) : { : print(); del(); : 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.134.141

04/29 21:52, , 1F
沒有清除phead?
04/29 21:52, 1F
文章代碼(AID): #19-5NJCe (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #19-5NJCe (C_and_CPP)