今天我們來學習動態創建鏈表!!!
動態創建鏈表:分為頭插法和尾插法
頭插法(動態創建):
頭插法就是讓新節點變成頭
代碼如下
? ? ? ? ? ? ? ? ? ? ? ?? ??
????????吐血了:這邊有個非常重要的知識點,這邊第三個if這里一定要將new->next初始化為NULL,因為這個if的條件就是當這個head為NULL,new做頭的時候,所以此時傳過來的new就是做頭的,就只有它這一個,沒有下一個,所以如果不初始化new里面的next的話,那么就會發生未定義的行為,就是個野指針,那么在遍歷的時候,由于new->next沒有初始化就會發生未定義的行為,就會發生死循環且是看不懂的循環比如:
非常的可怕!差點給我嚇暈了
? ? ? 但是在Linux的虛擬機上面運行又不會出現這樣的情況,因為windows和Linux的一些庫和處理方式的不同吧,但是還是要加上new->next = NULL,這樣才符合邏輯。
頭插法代碼
#include <stdio.h>
#include <stdlib.h>
struct Test
{
?? ?int data;
?? ?struct Test *next;
};
struct Test *insertDataBeforeHead(struct Test *head)
{
?? ?struct Test *new = NULL;
?? ?while(1){
?? ??? ?new = (struct Test *)malloc(sizeof(struct Test));
?? ??? ?if (new == NULL)
? ? ? ? {
? ? ? ? ? ? printf("內存分配失敗\n");
? ? ? ? ? ? return head;
? ? ? ? }
?? ??? ?printf("請輸入data\n");
?? ??? ?scanf("%d",&(new->data));
?? ??? ?if(new->data == 0){
?? ??? ??? ?printf("0 quit\n");
?? ??? ??? ?return head;
?? ??? ?}
?? ??? ?if(head == NULL){
?? ??? ??? ?head = new;
?? ??? ??? ?new->next = NULL;//太關鍵了這個
?? ??? ?}else{
?? ??? ??? ?new->next = head;
?? ??? ??? ?head = new;
?? ??? ?}
?? ?}
?? ?return head;
}
void printfInfo(struct Test *head)
{
?? ?struct Test *point;
?? ?point = head;
?? ?while(point !=NULL){
?? ??? ?printf("%d ",point->data);
?? ??? ?point =point->next;
?? ?}
?? ?putchar('\n');
}?
int main()
{
?? ? struct Test *head = NULL;
?? ? head = insertDataBeforeHead(head);
?? ? printfInfo(head);
?? ? return 0;
}
demo如上各位友友們,盡情享受......
明天學習頭插法的優化補充!