【发布时间】:2020-02-26 07:13:24
【问题描述】:
我正在尝试编写一个“add”函数,该函数接受节点中保存的值(表示为“n”),以及节点要添加到链表中的位置(表示为“pos”)。
我看到有 3 个单独的添加函数的代码 - addAtBeginning、addAtMiddle、addAtEnd,但我想要一个添加函数来完成所有这些。
我已经为 add(int n, int pos) 编写了代码,但它没有给我预期的输出。
例如,在我的主目录中,我有:
LinkedList num;
num.add(5,1);
num.add(6,2);
num.add(7,2);
num.printList();
我期待输出:5 7 6,(因为 7 将移动到第二个位置,然后 6 将移动到第三个位置),除了我得到输出:5 6 7,其中 7被添加到第三个位置。
另外,我已经编写了 Node 类和 LinkedList 类。我一直在以较小的增量在这些类中测试我的函数,除了我的 add 函数之外,其他一切似乎都很好。
Node * newNode = new Node();
newNode->setValue(n); //Node gets value n
int i=1; //ie. first position is 1, not 0
Node * current = head;
if (current == nullptr) //ie. then new node IS the head
{
head = newNode;
head->next=nullptr;
return;
}
if (current->next==nullptr) //adding to end of list
{
current->next = newNode;
newNode->next = nullptr;
}
else //if inserting Node at middle, (neither at beginning or end)
{
while ( i<pos && current->next != nullptr) //traverse thru list
{
current=current->next;
i = i+1;
}
Node * oldNext = current->next;
current -> next = newNode;
newNode -> next = oldNext;
}
编译时没有错误信息。
【问题讨论】:
-
如果用户要求在位置 6 插入一个节点,但节点数少于 5 个,应该在哪里插入节点?你应该插入节点吗?
-
if (current->next==nullptr) //adding to end of list是如何工作的?current->next只检查节点 2。如果列表的末尾是节点 3 怎么办? -
建议:画图。从一个空列表开始。绘制一个未连接的节点。绘制您需要建立的所有连接以将此节点添加到列表中。然后在将节点添加到末尾时逐步重绘列表,然后在开头插入节点时再次重新绘制。然后再次在列表中间插入一个节点。这些图纸应该描述所有的情况。然后查看您必须执行的步骤中是否有任何重复,您可以利用这些重复来减少您必须涵盖的不同案例的数量。
标签: c++ linked-list nodes singly-linked-list