【发布时间】:2019-08-14 11:53:50
【问题描述】:
我在 leetcode 上学习链表时编写了这段代码。在这个问题中,最后,在使用索引 6 调用 deleteAtIndex 函数的地方,屏幕变为空白。它适用于索引有效的所有其他值。但是对于索引的无效值,没有输出。
/*Delete the index-th node in the linked list, if the index is valid.
Below is the function I wrote.*/
void deleteAtIndex(int index) {
Node* current =start;
int x=0;
int i;
while(current != NULL){
x++;
current = current->next;
}
if(index == 0){
current =start;
start = current->next;
}
else if(index >0 && index <=x ){
current =start;
for(i=0; i<index-1; i++){
current = current ->next;
}
current->next= current->next->next;
}
if (index > x || index < 0) {
cout << "Invalid Index" << endl;
}
return;
}
【问题讨论】:
-
在 C++ 标准库中有很多类似列表的容器,所以你不需要自己实现。
-
尝试调试代码
-
显示minimal reproducible example,包括最小输入(如果有)以及实际和预期输出问题可能出在
deleteAtIndex函数之外的其他地方。 -
尝试删除列表的last节点时出现问题。拿一张纸和一支铅笔,画一个包含例如 2 个元素的链表。您应该能够弄清楚为什么删除列表的最后一个元素不起作用。
标签: c++ list function singly-linked-list definition