构建链接列表结构时。我已经学会了正确的做法,但我不知道为什么更简单的方法不起作用。我搜索了互联网,我买了一本书,我玩了代码和理论,我终于说它退出,并愿意处理我的问题,如果我只是错过了一些消极的东西。所以这里是:为什么在构建链接列表时我必须指向一个指针C++
#include <bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node* next;
// Constructor
Node(int data)
{
this->data = data;
next = NULL;
}
};
// Class to represent Red-Black Tree
class LinkedList{
private:
Node* root;
public:
// Constructor
LinkedList() { root = NULL; }
//insert new value into list
void insert(const int n);
//print all values from root to end;
void print();
};
// Function to insert a new node with given data
void LinkedList::insert(const int data){
Node** pp = &root;
while (*pp)
pp = &((*pp)->next);
*pp = new Node(data);
}
void LinkedList::print(){
Node** pp = &root;
while (*pp){
cout << (*pp)->data << " ";
pp = &((*pp)->next);
}
cout << endl;
}
int main(){
LinkedList ll;
ll.insert(5);
ll.insert(2);
ll.insert(22);
ll.print();
return 0;
}
很简单的东西,它运行的很好。但是,这是一个问题。因为我不知道为什么我不能做到这一点:
void LinkedList::insert(const int data){
Node* pp = root;
while (pp)
pp = pp->next;
pp = new Node(data);
}
应该做同样的事情我看到指针在我的头上的方式。当我在纸上写下地址/内容对时,它仍然有意义。
谢谢, -Connor。
如果'root'是空会发生什么? – vu1p3n0x
你会 - 如果你只做'pp = pp-> next;'。在附注中,您不应该包含''。相反,请按照所用功能的文档中的说明包含适当的标题。 –
SergeyA
vu1p3n0x - 如果root为空,'(pp)'应该可以捕捉到。 SergeyA - 没有任何回报。 但也许这是所有返回到根为空时的问题。但我不明白为什么这很重要。不应pp也为空,因此while循环永远不会被调用。 –