c中的指针:删除链表的每个第二个元素的函数

时间:2012-07-19 17:25:29

标签: c pointers linked-list

我想编写一个函数,它获取指向链表头的指针,并从列表中删除每个第二个成员。 List是元素的链接元素:

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;
            }
        }
    }

我一直在改变它,因为我一直在发现错误。你能指出任何可能的错误吗?

2 个答案:

答案 0 :(得分:9)

如果您根据节点对考虑链接列表,则算法会简单得多。循环的每次迭代都应该处理两个节点 - headhead->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);
}

答案 1 :(得分:1)

以递归术语显示此问题可能是最直接的,例如:

// outside code calls this function; the other functions are considered private
void deletdscnds(element* head) {
  delete_odd(head);
}

// for odd-numbered nodes; this won't delete the current node
void delete_odd(element* node) {
  if (node == NULL)
    return; // stop at the end of the list
  // point this node to the node two after, if such a node exists
  node->next = delete_even(node->next);
}

// for even-numbered nodes; this WILL delete the current node
void delete_even(element* node) {
  if (node == NULL)
    return NULL; // stop at the end of the list
  // get the next node before you free the current one, so you avoid
  // accessing memory that has already been freed
  element* next = node->next;
  // free the current node, that it's not needed anymore
  free(node);
  // repeat the process beginning with the next node
  delete_odd(next);
  // since the current node is now deleted, the previous node needs
  // to know what the next node is so it can link up with it
  return next;
}

对我来说,至少,这有助于澄清每一步都需要做些什么。

我不建议实际使用这种方法,因为在C中,递归算法可能占用大量RAM并导致堆栈溢出,而编译器不会优化它们。相反,dasblinkenlight的答案包含您应该实际使用的代码。