不明白将新项目附加到链接列表(在开始和结束时)时的错误

问题描述 投票:0回答:2

如上所述,我似乎无法理解代码中的错误,我在这段特定的代码中做错了什么:

Node 是这样写的:

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

这是开头的附加:

void Shift(struct Node **head, int new_data) {
    struct Node *New;
    
    New = (struct Node *)malloc(sizeof(struct Node));
    if (New == NULL) {
        printf("It is Null\n");
    }
    New->data = new_data;
    New->link = head;
}

这是最后的追加:

void Shift(struct Node *head, int new_data) {
    
    while (head !=  NULL) {
        head = head->link;
    }
    struct Node *New;
    New = (struct Node *)malloc(sizeof(struct Node));
    if (New == NULL) {
        printf("It is Null\n");
    }
    New->link = NULL;
    New->data = new_data;
    

如果有人知道发生了什么,请告诉我要添加什么以及为什么。预先感谢!

我查了一下,它说我必须这样做

head->link = new
,但这会导致永无止境的数字级联......

c linked-list singly-linked-list
2个回答
0
投票

我看到的第一件事是这两个函数都被命名为“Shift”,因此其中一个需要重命名。

另外这一行:

New->link = head;

不正确,因为“head”在函数参数中被定义为指向指针 (**) 的指针,但“New->link”只是一个指针 (*)。您不能直接将这些变量之一分配给另一个。

由于在另一个函数中您只使用指针,因此正确的解决方案似乎是删除该行中“head”参数附近的一颗星:

void Shift(struct Node *head, int new_data){

获得:

void Shift(struct Node *head, int new_data){

这段代码应该可以编译。

如果您确实想将指针传递给函数的指针,您应该将赋值更改为:

New->link = *head;

0
投票

存在多个问题:

  • 如果内存分配失败则不会返回。

  • 第一个版本(在列表调试时插入)无法正确处理

    head
    :它是指向列表头节点的指针,因此
    New->link
    必须设置为
    *head
    并且
    *head
    必须设置为更新成为新负责人:
    *head = New;
    .

  • 第二个版本会跳过节点,直到

    head
    为空指针,如果将新节点链接为其
    next
    节点,则会导致未定义的行为。

  • 附加到列表末尾的第二个版本也应该采用

    struct Node **head
    ,以便在列表为空时可以更新列表的头部。

以下是修改后的版本:

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

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

void Shift(struct Node **head, int new_data) {
    struct Node *New = malloc(sizeof(struct Node));
    if (New == NULL) {
        printf("Shift: Memory allocation error\n");
        return;
    }
    New->data = new_data;
    New->link = *head;
    *head = New;
}

void Append(struct Node **head, int new_data) {
    struct Node *New = malloc(sizeof(struct Node));
    if (New == NULL) {
        printf("Append: Memory allocation error\n");
        return;
    }
    New->data = new_data;
    New->next = NULL;
    if (*head) {
        struct Node *last = *head;
        while (last->next)
            last = last->next;
        last = New;
    } else {
        *head = New;
    }
}

Append
函数可以这样简化:

void Append(struct Node **head, int new_data) {
    struct Node *New = malloc(sizeof(struct Node));
    if (New == NULL) {
        printf("Append: Memory allocation error\n");
        return;
    }
    New->data = new_data;
    New->next = NULL;
    while (*head) {
        head = &(*head)->next;
    }
    *head = New;
}
© www.soinside.com 2019 - 2024. All rights reserved.