仅显示上次输入的值的链表

Linked List Only Showing Last Value Entered

本文关键字:链表 输入 显示      更新时间:2023-10-16

我正在努力变得更熟练地使用链表。我看了好几个视频,读了很多论坛帖子,但我还是有问题。我试图从一个简单的链表开始。但是,对于我的当前代码,只打印最后一个值。如果有人能向我解释我做错了什么,我将不胜感激。此外,我通常在main.cpp文件中定义我的所有函数。然而,它不允许我为我的链接列表这样做。此外,在main.cpp文件中定义所有函数是一种好的做法还是我应该打破的习惯?

提前感谢:)。以下是我的链接列表文件:

  #pragma once
#include <iostream>
using namespace std;
class LinkedList {
    struct node {
        int data;
        node *next;
    };
public:
    LinkedList() {
        head = NULL;
    }
    node *newNode;
    node *temp;
    node *head;
    void insertData(int value) {
        newNode = new node;
        newNode->data = value;
        temp = newNode;
        head = newNode;
        temp->next = newNode;
        temp = temp->next;
        newNode->next = NULL;
    }
    void printList() {
        node *print;
        print = head;
        while (print != NULL) {
        cout << print->data;
        print = print->next;
        }
    }
};

这是我的主.cpp文件

#include <iostream>
#include "LinkedList.h"
using namespace std;
int main() {
    LinkedList list;
    list.insertData(1);
    list.insertData(2);
    list.insertData(3);
    list.printList();

    system("pause");
    return 0;
}
void insertData(int value) {
    newNode = new node;
    newNode->data = value;
    temp = newNode;
    head = newNode;
    temp->next = newNode;
    temp = temp->next;
    newNode->next = NULL;
}

在您的代码中,head = newNode接受head所指向的任何内容,并将其抛出以支持newNode。从本质上讲,每次尝试在列表中插入新值时,都会丢弃整个列表。

相反,你的插入应该做一些类似的事情

void insertData(int value) {
    newNode = new node; //Create ourselves a new node
    newNode->data = value; //Put the proper value in
    newNode->next = head; //Make it so the whole list is after our node
    head = newNode; //Make our node the first in the list
}

我建议您更改代码中的其他一些内容,比如将newNodetemp作为成员变量,而它们可能只是函数的本地变量,以及缺少析构函数。但是您的打印功能应该可以使用修改后的插入(请参阅此处的运行)。