【问题标题】:Insert linked list插入链表
【发布时间】:2016-06-04 14:42:55
【问题描述】:

我正在尝试将一个简单的节点插入到链表的最后一个位置。但是我遇到了麻烦。

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

using namespace std;

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

Node* Insert(Node* head, int data);
Node* print(Node* head);
void ReverseIterative();


Node* Insert(Node* head, int data)
{
    Node* newNode;
    newNode->data = data;
    newNode->next = NULL;

    if(head == NULL)
    {
        return newNode;
    }

    Node* curr=head;
    while(curr->next!=NULL)
    {
        curr=curr->next;
    }
    curr->next = newNode;
    return head;
}

Node* printList(Node* head)
{
    while(head)
    {
        cout<<head->data;
        head=head->next;
    }
    cout<<endl;
}

int main()
{
    struct Node* head = NULL;
    head = Insert(head, 2);
    head = Insert(head, 4);
    printList(head);
    return 0;
}

我不确定我做错了什么。请帮忙~!我检查了我的逻辑,一切都应该是正确的。这可能是我在 insert() 中创建新节点的方式。我认为我的语法有问题,但我不确定它是什么。我真的很讨厌这种情况发生......

感谢您的帮助

【问题讨论】:

  • “遇到麻烦”不能很好地描述您的问题,是吗?请具体
  • 为什么你会认为这是你的语法?您是否收到编译器错误?如果有,那是什么?
  • 停止查看代码并使用调试器单步执行代码的最佳时机。指针会指向。你的一个没有。
  • 你永远不会在这条线上分配newNodeNode* newNode;
  • @Telenoobies “代码是可编译的,” 这是在调试器中运行代码的请求的非常错误的响应。经常出现,而且总是走错路。

标签: c++ linked-list


【解决方案1】:

在您的 Insert 函数中,您永远不会分配 newNode

Node* newNode;

你需要像这样分配它:

Node* newNode = new Node();

修复此问题后程序正常运行,输出为:

24

http://ideone.com/16XL5W

编辑: 关于您在下面的评论,以下几行不分配任何东西

Node* newNode;
struct Node* newNode;

它们只是声明变量,因为您已将它们标识为指针 (*)。指针只是指向堆上的一个对象。为了真正在堆上创建一个对象,你需要使用new Node()

您的程序崩溃的原因是因为您试图从尚未初始化的指针访问内存。

如果需要,您可以使用 malloc,但您使用 C++ 进行编程,因此作为一般规则,除非您确实需要,否则切勿使用 malloc

如果您使用的是兼容的编译器,请使用shared_ptrs,那么您永远不必担心deleteing 您new 的事情。

【讨论】:

  • 请注意,将共享指针用于链表may have serious deficiencies 会限制这些分配深度。
  • @πάνταῥεῖ 好点。在这种情况下它没有多大意义,但在更高级的应用程序中,shared_ptrs 在大多数情况下是首选。
  • 我现在正在阅读 C 编程语言。示例之一是 Struct point makepoint(int x, int y) { struct point temp; ...返回温度;它不做 struct point temp = new point()
  • 在这种情况下,它正在调用一个返回 point 对象(不是指针)的函数。您应该真正了解堆分配和堆栈分配之间的区别。
  • 看看这个人的例子。 youtu.be/sYcOK51hl-A?t=12m4s 在他的反转函数中,他只有 struct Node *curr, *pre, *next。我很困惑...
【解决方案2】:

除了Node* newNode分配(未初始化变量错误),下面会抛出返回值错误:

Node* printList(Node* head)
{
    while (head)
    {
        cout << head->data;
        head = head->next;
    }
    cout << endl;
}

您已将Node* 设置为返回类型,但此函数没有return 值。因为这个函数正在打印你的列表,所以它不需要返回任何东西。将返回类型更改为void

【讨论】:

    猜你喜欢
    • 2017-08-27
    • 2013-02-28
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    • 2012-02-18
    相关资源
    最近更新 更多