當我有下面的代碼:Ç段錯誤試圖實現的LinkedList
#include <stdio.h>
#include <stdlib.h>
#define MAXN 100
typedef int key;
typedef int data;
struct list * createElement(key k, data info);
struct list{
key k;
data info;
struct list *next;
};
struct list *L;
void init(key k, data info)
{
L = createElement(k, info);
}
struct list * createElement(key k, data info)
{
struct list *temp;
temp = (struct list *) malloc(sizeof(*temp));
temp->k = k;
temp->info = info;
return temp;
}
void insert(struct list * element)
{
element->next = L;
L = element;
}
void insertBefore(struct list * element, key k)
{
struct list * currentElement = L;
while(currentElement != NULL)
{
if(currentElement->k == k)
{
struct list *temp = currentElement;
currentElement = element;
currentElement->next = temp;
return;
}
currentElement = currentElement->next;
}
}
void insertAfter(struct list * element, key k)
{
struct list * currentElement = L;
while(currentElement != NULL)
{
if(currentElement->k == k)
{
struct list *temp = currentElement->next;
currentElement->next = element;
element->next = temp;
return;
}
currentElement = currentElement->next;
}
}
void deleteElement(struct list * element)
{
struct list * currentElement = L;
while(currentElement != NULL)
{
if(currentElement == element)
{
struct list * temp = currentElement;
currentElement = currentElement->next;
free(temp);
return;
}
currentElement = currentElement->next;
}
}
struct list * getElementByKey(key k) {
printf("\n1");
struct list *currentElement = L;
printf("2");
while(currentElement != NULL)
{
printf("3");
if(currentElement->k == k)
{
printf("4");
return currentElement;
}
printf("5");
currentElement = currentElement->next;
printf("6");
}
printf("There is no such element in the list");
}
struct list * pop()
{
struct list *element = L;
L = L->next;
return element;
}
int main()
{
init(0, 13);
struct list * element = createElement(5, 155);
insert(element);
struct list * k = createElement(7, 243);
insert(k);
//insertBefore(createElement(3, 100), 5);
printf("The first element value is: %d", pop()->info);
printf("The second element value is: %d", pop()->info);
printf("The element value is: %d", getElementByKey(5)->info);
return 0;
}
所以,當我執行它的調試器給我segmantation故障上線84這是if(currentElement->k == k)
的方法getElementByKey。我知道我試圖訪問一個未知的元素(因爲我使用pop方法,它刪除了列表中的第一個元素),但它應該打印出一條警告消息。似乎前一個元素的關鍵字有問題,或者我沒有注意到。
在標題尼斯錯字,順便說一句... ;-) – alk 2013-04-06 12:58:16
是,由於只注意到它 – user1113314 2013-04-06 13:07:53