我有这些类(为了便于阅读而剥离)
class node {
public:
int x;
node* next;
node(){}
~node(){}
};
class intLinkedList{
public:
intLinkedList();
~intLinkedList();
void Add (int newX);
private:
node* root;
};
Run Code Online (Sandbox Code Playgroud)
这是Add中的实现
void intLinkedList::Add (int newX){
node* newNode = new node();
newNode->x = newX;
newNode->next = NULL;
std::cout << "\n\n" << root << "\n\n" << std::flush;
if (root == NULL){
root = newNode;
return;
}
node * current;
current = root;
while (current->next != NULL){
current = current->next;
}
current->next = newNode;
return;
}
Run Code Online (Sandbox Code Playgroud)
当我在设置后立即打印出root指向的地址时,它会显示一个有效的地址.但是,下次调用Add时,root再次变为NULL.我无法想象造成这种情况的行为.绝对没有其他用途.
我完全意识到我缺少一些简单的东西.如果你倾向于投票,因为问题很简单,那就把它带到其他地方.这个平台的目的是让编码人员在我们进行编码脑力训练时聚在一起互相帮助.
编辑:这是驱动程序.
#include <string>
#include <iostream>
#include "intLinkedList.h"
using namespace std;
void AddValue(intLinkedList MyList);
void GetValue(intLinkedList MyList);
void InsertValue(intLinkedList MyList);
void DeleteValue(intLinkedList MyList);
void PrintList(intLinkedList MyList);
int main(){
intLinkedList MyList;
int Option;
while (true){
cout << "\n\nMain Menu\n---------\n\n1) Add Value\n2) See Value\n3) Insert Value at Position\n4) Delete Value at Position\n5) Print List\n6) Exit\n\n";
cin >> Option;
switch (Option){
case 1: AddValue(MyList); break;
case 2: GetValue(MyList); break;
case 3: InsertValue(MyList); break;
case 4: DeleteValue(MyList); break;
case 5: PrintList(MyList); break;
case 6: exit(0);
}
}
}
void AddValue(intLinkedList MyList){
int NewValue;
cout << "What value should be added?\n";
cin >> NewValue;
MyList.Add(NewValue);
}
void GetValue(intLinkedList MyList){
int Position;
cout << "What position do you want the value of?\n";
cin >> Position;
MyList.Get(Position);
}
void InsertValue(intLinkedList MyList){
int Position;
int NewValue;
cout << "What position do you wnat to insert after?\n";
cin >> Position;
cout << "\nWhat value do you want to insert?\n";
cin >> NewValue;
MyList.Insert(NewValue, Position);
}
void DeleteValue(intLinkedList MyList){
int Position;
cout << "What position do you want to delete?\n";
cin >> Position;
MyList.Delete(Position);
}
void PrintList(intLinkedList MyList){
cout << MyList.Print();
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句:我想知道人们为什么要编写链表实现?为什么不使用c ++标准库?
void AddValue(intLinkedList MyList);
Run Code Online (Sandbox Code Playgroud)
这会生成一个完整的新MyList项.你应该使用参考!
void AddValue(intLinkedList& MyList);
Run Code Online (Sandbox Code Playgroud)
编辑:
你为什么用
case 1: AddValue(MyList); break;
Run Code Online (Sandbox Code Playgroud)
代替:
MyList.Add(...);
Run Code Online (Sandbox Code Playgroud)
任何一种间接都会增加错误,复杂性和不可读性的风险.你的问题就是一个很好的例子!
这是我看到的第一个.也许还有更多.
希望这是一个切入点.