单链表分配问题 (nullptr)
Singly Linked List assign issue (nullptr)
这个简单的链表有什么问题?
// linked_lst1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
class Node
{
int data;
Node* next;
friend class LinkedList;
};
class LinkedList
{
private:
Node* s;
public:
LinkedList() : s(NULL)
{};
void add(int x)
{
Node* s1 = new Node();
s1 = s;
if (!s1)
{
s->data = x;
return;
}
while (s1->next)
s1 = s1->next;
Node* temp = new Node;
temp->data = x;
s1->next = temp;
temp->next = NULL;
}
void showList()
{
Node* s1 = new Node;
s1 = s;
while (s1)
{
cout << s1->data << " ";
s1 = s1->next;
}
}
};
这是主要部分:
int main()
{
LinkedList list;
list.add(3);
list.showList();
return 0;
}
我认为s->data = x;
中存在分配问题,但我不知道如何解决...
请注意,这只是一个教育性的简单代码,我不想使用模板等。
我想,我错了什么。
你创建一个新节点,然后立即覆盖 s1 以指向 s 指向的任何内容——你将失去对新创建的节点的所有访问权限。
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 如何在自删除后将对象设置为nullptr
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 单链表分配问题 (nullptr)
- 在VS2013上实现nullptr时出现问题