【问题标题】:Why the following implementation overrides the elements/ or prints only one element为什么以下实现会覆盖元素/或仅打印一个元素
【发布时间】:2015-10-26 06:34:16
【问题描述】:

我正在尝试在 c 中实现链表。在元素的插入中,如果head不为NULL,我尝试在链表的开头添加一个节点 这是我的代码

#include<stdio.h>
#include<stdlib.h>
struct Node{
    int data;
    struct Node* next;
};

struct Node* head ;

 void insert(int data){

     struct Node* temp = (struct Node*) malloc(sizeof(struct Node));

    temp->data = data;
    if(head!=NULL){
        temp = head;
        head = temp;
     }

    temp -> next = NULL;
    head = temp;

 }


void print(){

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


int main(){
  head = NULL;
  insert(2);
  insert(3);
  insert(5);
  print();

    return 0;
}


但是在打印功能上,我只得到 2 作为输出。可能是什么原因?

【问题讨论】:

  • head!=NULL 时您的插入功能无法正常工作。您正在丢弃分配的 temp 节点。推荐阅读:How to debug small programs。在这种情况下,如果您在insert() 中添加一些打印,或者只是在将更改绘制到列表时手动考虑程序,您可能会自己解决问题。

标签: c pointers linked-list singly-linked-list


【解决方案1】:

函数的定义方式如下

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

    if ( temp != NULL )
    {
        temp->data = data;
        temp->next = head;

        head = temp;
    }
}

或者如下方式

_Bool insert( int data )
{
    _Bool success;

    struct Node *temp = ( struct Node * )malloc( sizeof( struct Node ) );

    if ( ( success = temp != NULL ) )
    {
        temp->data = data;
        temp->next = head;

        head = temp;
    }

    return success;
}

至于你的代码,当它不是第一个节点时,你总是分配 head 自己

if(head!=NULL){
    temp = head;
    head = temp;
 }

因此程序存在内存泄漏,并且列表总是包含第一个插入的元素。

当然,您还需要编写一个函数,在不再需要列表时释放所有分配的内存。

【讨论】:

  • head!=NULL 正在检查列表是否为空。但是您正在检查 temp!=NULL。我不明白
  • @gates temp != NULL 检查内存分配是否成功
  • mallocshould not be cast的结果
  • @gates 我检查内存是否分配成功。
  • 如果列表为空,则headNULL。所以temp-&gt;next = head 在这种情况下实际上将NULL 分配给temp-&gt;next
【解决方案2】:

这可能是插入函数

void insert(int n)
{
     if(head==NULL)
     {
           head=(struct Node*)malloc(sizeof(struct Node));
           head->data=n;
           head->next=NULL;
     }
     else
     {
           struct Node *temp=(struct Node*)malloc(sizeof(struct Node));
           temp->data=n;
           temp->next=head;
           head=temp;
     }

}

【讨论】:

  • head应该指向第一个节点,为什么要给它分配数据?
  • head 将指向第一个节点。如果我做了一个临时并分配了内存,最后是 head=temp,它会有同样的效果
  • 这并不能回答“为什么这不起作用?”的问题。此外,您要在列表的末尾插入,而问题是 @gates 正试图在列表的 beginning 处插入。这会使您的实现变得比需要的更复杂。
  • 好吧对不起,我误解了这个问题。我正在相应地改变
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-20
  • 1970-01-01
  • 2021-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多