gpt4 book ai didi

c++ - 打印双向链表 - 无结果

转载 作者:行者123 更新时间:2023-11-28 05:30:04 24 4
gpt4 key购买 nike

我是 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;

}

最佳答案

你需要设置头部。

  void appendToEnd(int val){
MagicSquaresNode *newNode = new MagicSquaresNode;
newNode->nodeIndex = val;

if(isEmpty()){
tail = newNode;
head = newNode;
} else {
tail->pright = newNode;
newNode->pleft = tail;
}

tail = newNode;
}

关于c++ - 打印双向链表 - 无结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39761169/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com