2014-10-04 105 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; 
    } 
}