我编写了代码来删除链表尾部的节点。该代码在不同的测试用例中正常工作,但我认为我使我的代码有点麻烦。但是,我不知道我可以做些什么不同的事情?
node_t *remove_t (node_t *l){
if (l==NULL){
return l;
}
else {
node_t *curr=l;
node_t *ret=l;
if (curr->next==NULL){
l=NULL;
return l;
}
else {
while (curr->next->next!=NULL){
curr=curr->next;
}
curr->next=NULL;
free(curr->next);
return ret;
}
}
}
最佳答案
如果您保留一个指向节点的指针到指针,然后迭代到列表的末尾并简单地释放最后一个指针并将其设置为NULL,那就容易得多
,例如
/** delete last node */
void del_last_node (node_t **l)
{
node_t **ppn = l; /* pointer to pointer */
node_t *pn = *l; /* pointer to node */
for (; pn->next; ppn = &pn->next, pn = pn->next) { } /* iterate to last */
free (*ppn); /* free node */
*ppn = NULL; /* set pointer NULL */
}
关于c - 删除链表尾部的节点 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58274796/