Печать связанного списка печатает только головной узел - PullRequest
0 голосов
/ 10 июля 2019

После случайного заполнения связанного списка колодой из 52 карт. Когда я пытаюсь распечатать его, он напечатает головной узел 52 раза. Что-то не так с моей «логикой прохождения через связанный список» или что-то не так с моей логикой вставки?

Это вспомогательные методы Node (у bagNode есть CardOfBag и следующий)

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;
}

Ответы [ 2 ]

1 голос
/ 10 июля 2019

bagNode :: setNext () должен указывать следующую точку для предоставленного узла; оставьте другой узел в покое:

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

Ваша сумка :: setCurrent () не работает. Вы должны заставить this-> current продолжать идти «дальше» до тех пор, пока не достигнете требуемой позиции, вместо этого вы просто меняете следующий указатель на ... то же значение, которое ранее имело .

Сделайте что-то вроде этого:

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

Теперь это должно работать лучше.

0 голосов
/ 10 июля 2019

в вашей функции

void bag::setCurrent(int desiredPosition)

Вы не меняете this-> current вообще.По сути, вы ничего не сделали в этой функции.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...