我想写一个函数,它获取一个指向链表头的指针,并从链表中每隔一个成员删除一次。 List 是 element 类型的链接元素:
typedef struct element{
int num;
struct element* next;
}element;
我是所有这些指针算法的新手,所以我不确定我写的是否正确:
void deletdscnds(element* head) {
element* curr;
head=head->next; //Skipping the dummy head//
while (head!=NULL) {
if (head->next==NULL)
return;
else {
curr=head;
head=head->next->next; //worst case I'll reach NULL and not a next of a null//
curr->next=head;
}
}
}
我一直在修改它,因为我一直在发现错误。能否请您指出任何可能的错误?
最佳答案
如果您根据节点对来考虑您的链表,则该算法会简单得多。循环的每次迭代都应处理两个节点 - head
和 head->next
,并使 head
等于 head->next ->next
退出时。同样重要的是不要忘记删除中间节点,如果您要将它从列表中删除,否则您将看到内存泄漏。
while (head && head->next) {
// Store a pointer to the item we're about to cut out
element *tmp = head->next;
// Skip the item we're cutting out
head->next = head->next->next;
// Prepare the head for the next iteration
head = head->next;
// Free the item that's no longer in the list
free(tmp);
}
关于c - c : Function which deletes every second element of linked list 中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11566138/