這是慕課網上邊的c語言結構體里面的課程,為什么第19行將p2->next 的指正指向了p1的地址,隨后又初始化p2,這樣不是直接吧p2->next的地址就不指向p1了不是么,求大神解答!
1 回答
kevinZee
TA貢獻50條經驗 獲得超39個贊
他把p1p2換來換去看上去確實有點難理解。
他的意思其實就是創建一個鏈表,利用一個變量來緩存和不斷更新尾節點的指針
我在你這個函數的基礎上簡單調整了一下,可能更便于你的理解
struct?weapon?*?create(){
????struct?weapon?*?head?=?NULL;
????struct?weapon?*?tail?=?(weapon?*)?malloc(sizeof(struct?weapon));
????scanf("%d?%d",&(tail->price),&(tail->atk));
????int?n?=?0;
????while(tail->price?!=?0){
????????n++;
????????if(n?==?1){
????????????head?=?tail;
????????}else{
????????????//創建一個新的節點
????????????struct?weapon?*?new_tail?=?(weapon?*)?malloc(sizeof(struct?weapon));
????????????scanf("%d?%d",&(new_tail->price),&(new_tail->atk));
????????????new_tail->next?=?NULL;
????????????//將這個新節點和當前的尾節點相連
????????????tail->next?=?new_tail;
????????????//更新尾節點指針
????????????tail?=?new_tail;
????????}
????}
????return?head;
}- 1 回答
- 0 關注
- 1501 瀏覽
添加回答
舉報
0/150
提交
取消
