我是 C++ 和一般编程的新手。我正在尝试实现一个双向链表。我认为该列表已成功创建,但我无法完全打印该列表。你能告诉我下面的 printListForward 方法有什么问题吗?我的代码还没有完成。也非常感谢任何提示和建议。
#include "MagicSquare.hpp"
#include <iostream>
class MagicSquaresList{
private:
struct MagicSquaresNode{
int nodeIndex;
MagicSquaresNode *pleft;
MagicSquaresNode *pright;
MagicSquaresNode *pup;
MagicSquaresNode *pdown;
};
MagicSquaresNode *head;
MagicSquaresNode *tail;
public:
MagicSquaresList (){
head = NULL;
tail = NULL;
}
int getListLength(){
int length = 1;
MagicSquaresNode *temp = new MagicSquaresNode;
temp = head;
if(isEmpty()){
return 0;
}else{
while(temp != tail){
length++;
temp = temp->pright;
}
}
return length;
}
bool isEmpty(){
return head == NULL;
}
void appendToEnd(int val){
MagicSquaresNode *newNode = new MagicSquaresNode;
newNode->nodeIndex = val;
if(isEmpty()){
tail = newNode;
} else {
tail->pright = newNode;
newNode->pleft = tail;
}
tail = newNode;
}
void printListForward() {
MagicSquaresNode *ptr = head;
while(ptr != tail){
std::cout << ptr->nodeIndex << " ";
ptr = ptr->pright;
}
std::cout << std::endl;
}
};
int main(){
/*********** temporary *****************/
int matrixSize, listSize;
matrixSize = 3;
listSize = matrixSize * matrixSize;
/****************************************/
MagicSquaresList list1;
for (int i = 1; i <= listSize; i++){
list1.appendToEnd(i);
}
list1.printListForward();
std::cout << list1.getListLength() << std::endl;
return 0;
}