重拾c語言——鏈表

動態數據結構:不用事先定義好固定的內存空間
靜態鏈表
#include <stdio.h>
struct weapon{
 int price;
 int atk;
 struct weapon * next;//用來存放下一個節點的地址
};

int main(){
 struct weapon a ,b ,c, *head;
 a.price=100;
 a.atk=100;
 b.price=200;
 b.atk=200;
 c.price=300;
 c.atk=300;
 head=&a;
 a.next=&b;
 b.next=&c;
 c.next=NULL;
 
 struct weapon *p;
 p=head;
 while(p!=NULL){
   printf("%d,%d\n",p->atk,p->price);
   p=p->next;
}

return 0;


}


動態鏈表

#include <stdio.h>
struct weapon{
 int price;
 int atk;
 struct weapon * next;//用來存放下一個節點的地址
};

struct weapon * create(){       //創建鏈表的函數
  struct weapon *head;    
  struct weapon *p1,*p2;         //一個指向鏈表當前新創建的節點,一個用來指向上一個節點
  int n=0;     //用來記錄當前鏈表中的節點個數
  p1=p2=(struct weapon*) malloc(sizeof(struct weapon));   //malloc分配內存塊的函數 sizeof判斷數據類型的長度符
  scanf("%d,%d",&p1->price,&p1->atk);//第一個節點單獨做處理
  head=NULL;//因爲開始時鏈表不存在,所以賦給head一個初值
  //
  while(p1->price!=0){
    n++;
    if (n==1) head=p1;
    else p2->next=p1;

   p2=p1;
   p1=(struct weapon*) malloc(sizeof(struct weapon));
   scanf("%d,%d",&p1->price,&p1->atk);
   
 }
 
  p2->next=NULL;
  return (head);

 

}
int main(){

 struct weapon *p;
  p=create();
  printf("%d,%d",p->price,p->atk);

return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章