【问题标题】:I cannot display the linked list in c++我无法在 C++ 中显示链表
【发布时间】:2021-11-11 08:28:57
【问题描述】:

我有一个问题,我创建了一个新节点。 然后我创建了一个新节点,在开头插入并显示它的显示。 然后我创建了另一个节点将其插入到最后,但我无法在显示功能中显示它。 谁能告诉我这里有什么问题? 对于最终的链表,实际上并没有显示出来。

代码如下:

#include<iostream>

using namespace std;
void createlinklist();
void insertatfirst();
void insertatend();
void display();
struct node {
    int data;
    node * link;
};
node * start = NULL;
node * location = NULL;
void createlinklist() {
    node * temp = new node;
    cout << "Enter data in first node";
    cin >> temp -> data;
    temp -> link = NULL;
    start = temp;
    location = temp;
}
void insertatfirst() {
    node * temp = new node;
    cout << "Enter data for new node at the beginning ";
    cin >> temp -> data;
    temp -> link = NULL;
    start = temp;
    temp -> link = location;

    location = start;
    cout << "Linked first after inserting data at is ";
    while (location != NULL) {
        cout << location -> data;
        location = location -> link;
    }
    location = temp;
}
void insertatend() {
    node * temp = new node;
    cout << "Enter data for new node at the end ";
    cin >> temp -> data;
    temp -> link = NULL;
    location = start;
    while (location != NULL) {
        location = location -> link;
    }
    location -> link = temp;
    location = temp;

}

void display() {
    location = start;
    while (location != NULL) {
        cout << "The final linked list after ending at last node is ";
        cout << location -> data;
        location = location -> link;

    }
}

int main() {

    createlinklist();
    insertatfirst();
    insertatend();
    display();

}

【问题讨论】:

  • 您不会以您的显示方法移动到列表中的下一个元素。事实上,只要您的列表中至少有一个元素,您就可以在那里找到一个无限循环。
  • 先生,如果我删除 end() 函数处的插入,则显示确实会在第一个 () 函数处显示插入.. 显示未显示用于插入 end... 你能请帮我解决这个问题?
  • 我已经更新了显示功能中的代码,但还是不行。
  • 欢迎来到 Stack Overflow。请尝试遵循一些debugging 的建议,并尽可能专注于问题。
  • 您可能想查看有关如何构建链接列表的众多帖子之一。您已经掌握了基本概念,但稍作搜索肯定会帮助您找到问题的一些答案。

标签: c++ linked-list


【解决方案1】:

您的代码正在产生分段错误,请查看以下代码行:

while (location != NULL) {
  location = location -> link;
}
location -> link = temp;
location = temp;

您正在运行循环,直到 locationnull,然后分配 null -&gt; link = temp(因为 location 已经是 null)这是导致分段错误的原因。

改变

while (location != NULL)

while (location -> link != NULL)

在此之后一切都应该正常工作。

【讨论】:

  • 非常感谢!
猜你喜欢
  • 2021-10-13
  • 1970-01-01
  • 2021-08-12
  • 2020-01-26
  • 2017-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多