我是編程新手,以C開頭,我編寫了這個鏈表問題。我想我所做的是,你能幫我理解爲什麼鏈表上的下面的代碼給我一個分段錯誤錯誤?
- 頭指針作爲全球從任何地方訪問它並將其設置爲初始值爲null在插入代碼
- ,創建相同類型的新指針和分配內存,並給它的插入的數據。點頭指針到該第一插入數據電流
- 下一插入通過在頭部和迭代直到結束,使下一個的最後一個節點點的當前一個和電流爲null
- 類似地,對於顯示通在頭部和迭代,直到結束和打印
缺少什麼我在這裏有人可以幫我,爲什麼我會收到分段錯誤的第二輸入以及如何糾正呢? 是否應該對顯示功能進行任何更改?
#include<stdio.h>
#include<stdlib.h>
void insert(int data_add);
void display();
struct list
{
int data;
struct list *next;
} *head = NULL;
int main()
{
int data_add,n;
while(1)
{
printf("\n\n1.Add\n2.Display\n3.Exit\n");
scanf("%d",&n);
switch(n)
{
case 1: printf("\nEnter the element to add ");
scanf("%d",&data_add);
insert(data_add);
break;
case 2: printf("The nos are: ");
display();
break;
case 3: exit(1);
break;
default: printf("\nOpen your eyes");
}
}
}
void insert(int add)
{
struct list *current,*temp;
current = (struct list*) malloc (sizeof(struct list));
current->data = add;
if(head == NULL)
{
head = current;
current->next = NULL;
}
else
{
for(temp = head; temp!=NULL;temp = temp->next);
temp->next = current;
current->next = NULL;
}
}
void display()
{
struct list *current;
current = head;
while(current!=NULL)
{
printf("%d",current->data);
current = current->next;
}
}
在'插入()',你的'for'循環後找到列表的末尾,' temp'是'NULL' ...這個迭代太過分了。 – Dmitri