为什么我一直在显示我的链表?

时间:2018-06-03 12:06:11

标签: c++ linked-list

我是C ++的新手,目前正在学习链表。我在第一个在控制台上以某种方式显示我的链表的代码中遇到了这样的问题:

1 2
4

但是当我尝试构建它时,它会中断。我无法弄清楚原因。

这是代码

#include <iostream>
#include <conio.h>

using namespace std;

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

class list {
  node *head;

public:
  void display();
};

void list::display() {

  node *newnode;

  newnode = head->next;
  newnode->data = 2;
  newnode->next = new node;
  newnode->data = 2;
  newnode->next = new node;
  newnode->data = 1;
  cout << newnode->data;
  newnode->next = new node;
  newnode->data = 2;
  cout << "\t" << newnode->data;
  newnode->next = new node;
  newnode->data = 1;
  newnode->next = new node;
  newnode->data = 4;
  cout << endl;
  cout << newnode->data;
  newnode->next = NULL;
}

int main() {
  list ab;
  ab.display();
  _getch();
}

1 个答案:

答案 0 :(得分:0)

您没有将5分配给newnode,因此没有创建链接列表。

但是链接列表中的代码没有中断或其他任何内容,它会打印您想要的值,而不是链接列表。问题可能出在newnode->next,这在此代码中没有用处。移除conio.h#include <conio.h>

为了完全按照你想要的方式做你想要的,我们可以为getch_();创建一个构造函数,其中&#34;自动&#34;将数据添加到新节点。

然后在显示中,您必须说node等于newnode的下一个节点,这是某个数据的newnodenew node) 。只有这样才能创建链表。

newnode = newnode->next = new node(SOME_DATA)