C++ 链表奇怪的输出

标签 c++ linked-list

所以我一直在尝试编写一个链接列表。当我调试时或者如果我再添加一个这样的打印语句;

intlist.add_node(7);
intlist.print_list();
intlist.add_node(8);

打印精美;

5
7
5
7
8

但是如果我删除该语句,它只会打印三个八。调试也是如此,它似乎有效,但如果我只是运行它则不起作用。我不明白出了什么问题。 这是我的主要内容;

int main(){
  Linked_list intlist;
  intlist.add_node(5);
  intlist.add_node(7);
  intlist.print_list();
  intlist.add_node(8);
  intlist.print_list();
  return 0;
}

标题;

class Linked_list{
public:
  Linked_list();

  void add_node(int data);
  void remove_node(int data);
  int get_data(int index);
  void print_list();

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

  Node* head;
  int lenght;
};

以及头文件的源文件;

Linked_list::Linked_list(){
  head = 0;
  lenght = 0;
}

void Linked_list::add_node(int data){
  Node* newnode = new Node;
  newnode->data = data;
  newnode->next = NULL;
  if (head == 0) {head = newnode; lenght = 1; return;}
  else{
      Node* temp = new Node;
      temp = head;
      while (temp->next != NULL){
          temp = temp->next;

      }
      lenght++;
      temp->next = newnode;
      delete temp;
  }
}


void Linked_list::remove_node(int data){
    return;
}

int Linked_list::get_data(int index){
    return 0;
}

void Linked_list::print_list(){
    if (head == 0) {std::cout << "List is empty!!" << std::endl; 
    return;}
    else{
        Node* ptr = new Node;
        ptr = head;
        for (int i = lenght; i > 0; i--){
            std::cout << ptr->data << std::endl;
            ptr = ptr->next;
        }
    }
}

最佳答案

您的 add_node 函数应该是:

void Linked_list::add_node(int data) {

  Node* newnode = new Node;
  newnode->data = data;
  newnode->next = NULL;

  if (head == 0) {
      head = newnode;
      lenght = 1;
      return;
  } else {
      //Node* temp = new Node;
      Node *temp = head;
      while (temp->next != NULL) {
          temp = temp->next;
      }

      lenght++;
      temp->next = newnode;
      //delete temp;
  }
}

您不需要创建新的 Node 对象,因为您只想引用 head。 delete temp 实际上删除了 temp 先前指向的地址的内容,这是列表的最后一个元素。

关于C++ 链表奇怪的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44421863/

相关文章:

c - stat 结构的值包含结构丢失

c++ - 我的代码中的段错误(SIGSEGV)

c++ - Replace() 没有将字符串中的字符更改为应该替换的预期字符

c - 推送堆栈函数接收到我找不到的内存泄漏

c# - 从 C# LinkedList 中删除节点

data-structures - 你在业务编程中使用链表、双向链表等吗?

c++ - 为什么我可以在头文件中声明数组,但不能声明指针?

c++ - 从文本文件读取并保存到列表

c++ - 如何根据像素/高度确定线图的比例?

c - 释放后如何打印链表?