仅显示上次输入的值的链表
Linked List Only Showing Last Value Entered
我正在努力变得更熟练地使用链表。我看了好几个视频,读了很多论坛帖子,但我还是有问题。我试图从一个简单的链表开始。但是,对于我的当前代码,只打印最后一个值。如果有人能向我解释我做错了什么,我将不胜感激。此外,我通常在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
}
我建议您更改代码中的其他一些内容,比如将newNode
和temp
作为成员变量,而它们可能只是函数的本地变量,以及缺少析构函数。但是您的打印功能应该可以使用修改后的插入(请参阅此处的运行)。
相关文章:
- 反向给定链表中的K节点
- 如果没有malloc,链表实现将失败
- 文本文件中的单词链表
- 努力将整数转换为链表。不知道我在这里做错了什么
- 链表,反向函数,数据结构
- 使用std::list创建循环链表
- 链表的泛型函数remove()与成员函数remove)
- 为什么不能修改对象中的值?另外,我如何改进此链表?
- 我们可以删除链表中静态内存中的节点吗
- 修改链表主函数代码,用户将在其中输入节点的索引和数据以及正确的消息
- C++ 链表:它不会删除第一个输入
- 有没有办法将最初作为字符串输入的数字字符数组复制到双向链表中
- 获取用户输入以形成链表
- C++简体版链表,当我加载数据以创建链表并输入更多数据时,似乎存在差距
- 仅显示上次输入的值的链表
- 从用户输入创建和打印链表
- 链表输入类型问题
- 按第一个值和第二个值将输入排序到一个链表中
- 从文件中读取输入和写入链表的输出
- 从链表的.csv文件中读取输入