【问题标题】:Insert an element in end of a singly Linked List在单链表末尾插入一个元素
【发布时间】:2014-10-04 14:19:48
【问题描述】:

我从早上开始就一直在尝试修复此代码,但可以完成。所以,最后我需要一些帮助来找出错误。代码编译没有错误,但是当我从终端运行它时,我收到一条错误消息“分段错误: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); 
    } 
}

【问题讨论】:

  • 崩溃在哪一行?
  • temp1-&gt;next = temp; : temp1 是 NULL

标签: c linked-list


【解决方案1】:
  1. 您从不将head 设置为NULL 以外的任何值。

  2. (即使您修复了上述问题)temp1 保证在您到达 temp1-&gt;next = temp; 时为 NULL。

附:我认为将变量称为 temp、temp1 等并不是一个很好的做法。从这些名称中无法判断它们的假设功能是什么。

【讨论】:

    【解决方案2】:

    通常单链表有一个插入操作,在列表的开头插入数据。不过,您的功能插入可以如下所示

    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;
        }
    }
    

    如果你在函数中检查节点是否被分配会更好。

    Function Print 也是错误的。它看起来像

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

    【讨论】:

      【解决方案3】:

      你在写

      while(temp1 != NULL)
      

      变成这样

      while(temp1->next != NULL)
      

      这里,temp1 在循环结束时指向 null,并且您正在尝试在 null 之后添加节点,即

      null->next =temp;
      

      这一定是抛出错误。

      【讨论】:

        【解决方案4】:
        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; 
            } 
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-07-23
          • 2020-09-11
          • 2020-11-15
          • 2015-02-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多