我想实现一个下拉列表函数,该函数创建一个新列表,其中输入列表中的元素排除了前n个元素。我的方法是遍历列表并增加计数器,这样我就知道我在哪个节点,并开始在那个节点创建新列表。这里有什么问题?
// Create a list consisting of nodes of list, except the first n.
Node* drop_list(Node* list, int n) {
Node* result;
int counter = 0; //sets counter to 0
if (counter == n ){
Node* result = new_node(list->value, NULL); //creates the head of the note starting at the nth
node
for (Node* ntf = result; list->next != NULL; ntf = ntf->next) {
list = list->next; //updates list->value
ntf->next = new_node(list->value, NULL); //creates the rest of the new list
}
return result;
}
else {
list = list->next; //sets list value to the next node
counter++; //increments counter
}
}
如果是counter < n
,则永远不会进入复制节点的部分。请注意,尽管在else
-部分中增加了counter
,但之后将保留该函数。
一个简单的解决方案是在else
-部分递归调用drop_list
,例如像一样
}
else {
drop_list(list->next, n-1);
}
请注意,您必须检查诸如list
是NULL
、n
大于列表中的节点数等角点情况。
一般来说,我更喜欢这样一种解决方案,即使用循环移动到有问题的节点,然后开始复制。
BTW:你可以简单地将第n个节点作为列表的新头返回,而不是在删除节点之前复制节点,对吗?
这里的问题是,如果n将大于零,那么它将永远不会输入if(counter==n(。它将转到else块,在完成在else块中写的内容后,它将简单地返回。