gpt4 book ai didi

c++ - 打印链表只打印头节点

转载 作者:行者123 更新时间:2023-11-28 04:14:27 25 4
gpt4 key购买 nike

在用一副 52 张牌随机填充一个链表之后。当我尝试打印它时,它将打印头节点 52 次。是我的“遍历链表逻辑”有问题还是我的插入逻辑有问题?

这些是 Node 辅助方法(一个 bagNode 有一个 CardOfBag 和一个 next)

card *bagNode::getCard() // retreives card in the bagnode as pointer
{
return this->cardOfBag;
}
bagNode *bagNode::getNext() // retreives the next bagnode as pointer
{
return this->next;
}
void bagNode::setCard(card *card) // sets card of bagnode
{
this->cardOfBag = card;
}
void bagNode::setNext(bagNode *setNode) // sets next bagnode
{
setNode->next = this->next;
this->next = setNode;
}

这些是链表的方法(称为bag):它有一个头部、尾部和当前的 bagNode* 指针。

void bag::add(bagNode *node) // adds node to random position
{
int i, place, size;
place = randomPosition();
size = getCurrentSize();
if (size == 0) // for initial insertion into empty linked list
{
setHead(node);
setTail(node);
alterSize(1);
} else {
if ((size - 1) == place) // if the insertion is at the last node
{
this->tail->setNext(node);
setTail(node);
alterSize(1);
} else {
if (place == 0) // if insertion is at head node
{
node->setNext(this->head);
setHead(node);
alterSize(1);
} else {
setCurrent(place); // for any insertion in between first and last nodes
node->setNext(current->getNext());
current->setNext(node);
alterSize(1);
}
}
}
}

int bag::getCurrentSize() // returns size of bag (linked list)
{
return this->size;
}
void bag::alterSize(int num) // changes the size int of bag by num
{
this->size = this->size + num;
}
int bag::randomPosition() // generates random number from 0 to size exclusive
{
int size = getCurrentSize();
if (size != 0)
return (rand() % size);
}
void bag::setCurrent(int desiredPosition) // this traverses the current pointer
// by desiredPosition steps from the head node
{
int i;
this->current = this->head;
for (i = 0; i < desiredPosition; i++) {
this->current->setNext(this->current->getNext());
}
}
bagNode *bag::getCurrentNode() // returns node of current pointer
{
return this->current;
}

最佳答案

bagNode::setNext() 应该使 next 指向所提供的节点;留下另一个节点:

void bagNode::setNext(bagNode* setNode) //sets next bagnode                                                                              
{
this->next = setNode;
}

你的 bag::setCurrent() 不工作。您应该让 this->current 继续“下一个”,直到您达到 desiredPosition,而您只是将其 next 指针更改为...它之前具有的相同值。。 p>

改为做这样的事情:

void bag::setCurrent(int desiredPosition)                                                                                             
{
int i;
this->current = this->head;
for(i = 0; i < desiredPosition; i++)
{
this->current = this->current->getNext();
}
}

现在应该可以更好地工作了。

关于c++ - 打印链表只打印头节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56960607/

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