一:動態內存分配創建鏈表(鏈表的元素順序向後添加)
分析:順序向後添加的原理如下圖所示,主要定義p、q兩個指針
代碼如下:
struct Node *CList(){ //創建鏈表,新節點總順序向後
struct Node *head,*p,*q;
int ch;
head = (struct Node *) malloc(sizeof(struct Node));
head->next = NULL;
q = head;
scanf("%d",&ch);
while(ch!=9999){
p = (struct Node *) malloc(sizeof(struct Node)); //新建p節點
p->data = ch; //賦值
q->next = p;//連接鏈表
q = p;//q永遠向前移動
scanf("%d",&ch);
}
q->next = NULL;
return head;
}
運行結果:
二:動態內存分配創建鏈表(新添加的節點老是在頭結點之後)
分析:這種創建方式比較簡單,head的指針域總是放着最新節點的地址。
代碼如下:
struct Node *CreateList(){ //創建鏈表,新節點總在頭結點之後
struct Node *head,*p;
int i;
head = (struct Node *) malloc(sizeof(struct Node));
head->next = NULL;
scanf("%d",&i);
while(i!=9999){
p = (struct Node *) malloc(sizeof(struct Node));
p->data = i;
p->next = head->next; //將最新創建節點的指針域指向原來頭指針的下一個節點
head->next = p; //頭指針指向最新創建的節點
scanf("%d",&i);
}
return head;
}
運行結果: