【发布时间】:2021-12-14 13:33:12
【问题描述】:
链表有问题。需要创建一个方法,通过更改指针而不是创建新元素来替换列表中的数据。现在我有这样的方法:
void replaceValues(Node* head, int indexOne, int indexTwo)
{
Node* temporaryOne = NULL;
Node* temporaryTwo = NULL;
Node* temp = NULL;
Node* current = head;
int count = 0;
while (current != NULL) {
if (count == indexOne)
{
temporaryOne = current;
}
else if (count == indexTwo)
{
temporaryTwo = current;
}
count++;
current = current->next;
}
current = head;
count = 0;
while (current != NULL) {
if (count == indexOne)
{
head = temporaryTwo;
}
else if (count == indexTwo)
{
head = temporaryOne;
}
count++;
current = current->next;
}
}
我敢肯定,存在更简单的方法,如何做到这一点,但我不完全理解,它是如何工作的...... 提前感谢您的帮助。
【问题讨论】:
-
建议:不要编写一个庞大的函数,而是编写两个小实用程序:一个从列表中删除一个条目而不删除它,另一个在列表中插入一个已经存在的条目。考虑到这些,实现你的功能会容易得多。
-
“替换”是指“交换”吗?
-
所有任务都是这样的:创建函数将元素编号n替换为元素编号m。所以,也许交换。
标签: c++ pointers linked-list