0

我正在刷新我对 C++ OOP 的了解,但不确定为什么我可以进行这种遍历并添加到列表末尾并运行。在此背景下的任何建议将不胜感激。

    #include "stdafx.h"
    #include "LinkedList.h"

     LinkedList::LinkedList(void)
    {
    }


    LinkedList::~LinkedList(void)
    {
    }

        void LinkedList::add(Node* node)
           {
               Node* root = this->getRoot();
               if(root !=NULL)
                    {
//with two nodes the commented code worked 
                        //while(root->getNextNode() != NULL){}
                        //root->setNextNode(node);
//this part is culprit
                        Node* newNode = root->getNextNode();
                        while(newNode!=NULL)
                        {
                            newNode = newNode->getNextNode();
                        }
//I was thinking I am reaching to last node using this traversal
                        newNode = new Node(node->getData(),node->getNextNode());
                    }else
                    {
                        this->setRoot(node);
                    }

           };

    void LinkedList::traverseNodes()
        {
            Node* node = this->getRoot();
            printf("\ntraversing the nodes:");
            while(node != NULL){
                printf("%d", node->getData());
                node = node->getNextNode();
            }
        }
4

3 回答 3

0

当您达到 NULL 时为时已晚,您需要在之前跟踪节点。

void LinkedList::add(Node* node) {
  Node* current = this->getRoot();
  if (current != NULL) {
    while(current->getNextNode() != NULL) {
      current = current->getNextNode();
    }
    current->setNextNode(node); 
  } else {
    this->setRoot(node);
  }
};
于 2013-05-19T05:48:38.030 回答
0

您的代码的问题在于,一旦将指针设置newNodeNULL,将其指向新节点不会更改前一个节点。

试试这个:

Node* root = this->getRoot();
if (root != NULL) {
    Node* parent = root;
    while(true) {
        // two variables mean you have access to the previous node,
        // which is needed to add the next one.
        Node* child = parent->getNextNode();
        if (child != NULL) {
            parent = child;
        } else {
            parent->setNextNode(/* new node */);
            break; // EDIT
        }
    }
} else //...
于 2013-05-19T05:49:24.493 回答
0

该错误是因为您没有在末尾附加,实际上,您可以通过以下方式修复代码

   Node* previouseNode = this->getRoot();
   while(previouseNode->getNextNode() != NULL)
   {
       previouseNode = previouseNode->getNextNode();
   }
   //Next node of previouseNode is null so you can assign to it
   Node * newNode = new Node(node->getData(), previouseNode); // Maybe your list is bi-directional!
   previouseNode->setNextNode(newNode);
于 2013-05-19T05:49:26.067 回答