【问题标题】:Printing the singly linked list打印单链表
【发布时间】:2017-08-22 17:03:59
【问题描述】:

我是编程新手 在这里,我编写了一个使用链表接受和显示值的代码。 但是,代码采用所有值,但仅显示最后一个值 这是代码

#include <iostream>
using namespace std;
struct node {
    int value;
    node* next;
};
class llist {
public:
    void create();
    void display();
    node* head = NULL;
};
void llist::create()
{
    struct node* temp;
    temp = NULL;
    struct node* p;
    p = new struct node;
    cin >> p->value;

    if (head == NULL) {
        head = p;
    }

    else {
        temp = head;
        while (temp->next != NULL) {
            temp = temp->next;
        }
        temp->value = p->value;
        temp->next = NULL;
    }
}

void llist::display()
{
    struct node* temp = head;
    while (temp != NULL) {
        cout << "VALUE:" << temp->value << endl;
        temp = temp->next;
    }
}

int main()
{
    int n, i;
    llist l1;
    cin >> n;
    for (i = 0; i < n; i++)
        l1.create();
    cout << "Displaying list\n";
    l1.display();
    return 0;
}

输入:
4
1
2
3
4
显示列表
值:4

我想知道出了什么问题...

【问题讨论】:

  • 我建议使用调试器逐行检查您的代码,看看实际发生了什么。
  • 什么都没有
  • 你将node * next初始化成什么?
  • 什么都没有我会重新调查。确保您查看每一步的变量。编写代码后,您应该了解预期值是什么......
  • @ZIAANSARI “什么都没有” 你什么意思?你检查变量值了吗?他们都如你所愿吗?

标签: c++ singly-linked-list


【解决方案1】:

改变这个:

else {
    temp = head;
    while (temp->next != NULL) {
        temp = temp->next;
    }
    temp->value = p->value;
    temp->next = NULL;
}

到这里:

else {
    temp = head;
    while (temp->next != NULL) {
        temp = temp->next;
    }
    temp->next = p;
}

在链表末尾插入新元素时,会在 while 循环中找到最后一个元素,并将其放入 temp 变量中。然后将其next 值分配给新的p 元素。就像你以前做的那样,你只是覆盖了最后一个元素的整数。这就是为什么当您打印您的列表时,您只会得到您输入的最后一个数字。

另外,在创建新元素p时,一定要将其next值初始化为NULL

p = new struct node;
p->next = NULL;

【讨论】:

    【解决方案2】:

    问题在于 else 块中的最后 2 行。 您正在覆盖该值并仅在列表类中维护单一模式。这就是原因,只显示最后一个值。 替换

    temp->value = p->value;
    temp->next = NULL;
    

    temp->next = p;
    

    【讨论】:

      猜你喜欢
      • 2016-06-15
      • 2012-04-08
      • 2015-01-18
      • 2013-05-10
      • 2021-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-15
      相关资源
      最近更新 更多