首页 > 解决方案 > 自由链表

问题描述

我有一个链表,我想删除它的所有节点。问题是,如果我调用 delete 它只会打印出 1 然后它会冻结。我读过一些其他类似的问题,但我不知道为什么会这样。我想我只是瞎了眼什么的。

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

typedef struct _node {
  int id;
  struct _node *next;
} *node;

typedef struct {
  node first;
} *head;

head newHead(node n) {
  head h = malloc(sizeof(node));
  h->first = n;
  return h;
}

node newNode(int id) {
  node n = malloc(sizeof(node));
  n->id = id;
  n->next = NULL;
  return n;
}

void delete(head h) {
  if(h->first == NULL) return;

  node current = h->first;
  while(current != NULL) {
    printf("%i", current->id);
    node tmp = current;
    current = current->next;
    free(tmp);
  }

  // free(h);
}

int main() {
  node n = newNode(1);
  head h = newHead(n);
  node n2 = newNode(2);
  node n3 = newNode(3);
  node n4 = newNode(4);
  n->next = n2;
  n2->next = n3;
  n3->next = n4;

  printf("%i", h->first->id);
  printf("%i", h->first->next->id);
  printf("%i", h->first->next->next->id);
  printf("%i", h->first->next->next->next->id);

  delete(h);

  return 0;
}

标签: clinked-list

解决方案


在函数newNode中,您分配的内存大小无效

node n = malloc(sizeof(node));
                       ^^^^ 

这不是为类型的对象struct _node分配内存,而是为指向此类对象的指针分配内存struct _node *

你需要写

node n = malloc(sizeof(struct _node));

`

并且您需要释放指针指向的内存h

该功能delete可能看起来像

void delete( head *h ) 
{
    for ( node current = ( *h )->first; current != NULL; ) 
    {
        printf("%i", current->id);
        node tmp = current;
        current = current->next;
        free( tmp );
    }

    free( *h );

    *h = NULL;
}

并称为

delete( &h );

在这种情况下,退出函数后指针h将等于NULL

这是您更新的程序。

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

typedef struct _node {
  int id;
  struct _node *next;
} *node;

typedef struct {
  node first;
} *head;

head newHead(node n) {
  head h = malloc(sizeof(node));
  h->first = n;
  return h;
}

node newNode(int id) {
  node n = malloc(sizeof(struct _node));
  n->id = id;
  n->next = NULL;
  return n;
}

void delete( head *h ) 
{
    for ( node current = ( *h )->first; current != NULL; ) 
    {
        printf("%i", current->id);
        node tmp = current;
        current = current->next;
        free( tmp );
    }

    free( *h );

    *h = NULL;
}

int main() {
  node n = newNode(1);
  head h = newHead(n);
  node n2 = newNode(2);
  node n3 = newNode(3);
  node n4 = newNode(4);
  n->next = n2;
  n2->next = n3;
  n3->next = n4;

  printf("%i", h->first->id);
  printf("%i", h->first->next->id);
  printf("%i", h->first->next->next->id);
  printf("%i\n", h->first->next->next->next->id);

  delete( &h );

  return 0;
}

它的输出是

1234
1234

输出的第二行包含来自函数的测试消息delete


推荐阅读