2014-10-04 137 views
-4

自從早上我一直在嘗試修復此代碼,但可以完成此操作。所以,最後我需要一些幫助來弄清楚錯誤。代碼編譯沒有錯誤,但是當我從終端運行它,我得到一個錯誤說「segmetation錯誤:11」在單個鏈接列表的末尾插入元素

#include <stdio.h> 
#include <stdlib.h> 


struct Node{ 
    int data; 
    struct Node *next; 
}; 


struct Node *head; 


void Insert(int data); 
void Print(); 


int main() 
{ 
    head = NULL; //list is empty 

    Insert(3); 
    Insert(5); 
    Insert(2); 
    Insert(8); 

    Print(); 

    return 0; 
} 


void Insert(int data) 
{ 
    struct Node *temp = malloc(sizeof(struct Node)); 

    temp->data = data; 
    temp->next = NULL; 

    struct Node *temp1 = head; 

    while(temp1 != NULL) 
    { 
     temp1= temp1->next; 
    } 

    temp1->next = temp; 
} 


void Print() 
{ 
    struct Node *temp =head; 

    while(temp != NULL) 
    { 
     temp = temp->next; 
     printf("%d", temp->data); 
    } 
} 
+1

縮進你的代碼。 – gsamaras 2014-10-04 14:21:24

+0

它崩潰了什麼? – 2014-10-04 14:21:37

+0

'temp1-> next = temp;':'temp1'爲'NULL' – BLUEPIXY 2014-10-04 14:22:51

回答

0

通常,單鏈表具有插入操作,該操作將數據插入列表的開頭。儘管如此,您的功能插入可以看起來如下

void Insert(int data) 
{ 
    struct Node *temp = malloc(sizeof(struct Node)); 
    temp->data = data; 
    temp->next = NULL; 

    if (head == NULL) 
    { 
     head = temp; 
    } 
    else 
    { 
     struct Node *current = head; 
     while (current->next != NULL) current = current->next; 
     current->next = temp; 
    } 
} 

如果檢入函數是否分配節點會更好。

功能打印也是錯誤的。它可以像

void Print(void) 
{ 
    for (struct Node *current = head; current != NULL; current = current->next) 
    { 
     printf("%d ", current->data); 
    } 
} 
2
  1. 你從來沒有headNULL其他任何東西。

  2. (即使您修復上述問題)temp1保證爲NULL到達temp1->next = temp;時。

P.S.我不認爲這是一個很好的做法,叫你變量temp,temp1等。從這些名字是不可能告訴他們的假設功能是什麼。

0

你正在寫

while(temp1 != NULL) 

使它像這樣

while(temp1->next != NULL) 

這裏,temp1中指向空在循環的末尾,和你想空即後添加節點

null->next =temp; 

必須拋出錯誤。

0
struct Node *curr; 

void Insert(int data){ 
    struct Node *temp = malloc(sizeof(struct Node)); 
    temp->data = data; 
    temp->next =NULL; 

    if(head == NULL) 
     curr = head = temp; 
    else 
     curr = curr->next = temp; 
} 

void Print(){ 
    struct Node *temp =head; 
    while(temp != NULL){ 
     printf("%d ", temp->data); 
     temp=temp->next; 
    } 
}