我正在用C语言编写一个基本的链表程序,删除时遇到了一些麻烦。这是我所拥有的:

#include <stdio.h>

struct node * delete(struct node * head, struct node * toDelete);
void print(struct node * head);

struct node {
    int value;
    struct node *next;
};

int main(int argc, const char * argv[]) {

    struct node node1, node2, node3;
    struct node *head = &node1;

    node1.value = 1;
    node1.next = &node2;

    node2.value = 2;
    node2.next = &node3;

    node3.value = 3;
    node3.next = (struct node *) 0;

    print(head);

    delete(head, &node3);

    print(head);

    return 0;
}

struct node * delete(struct node * head, struct node * toDelete) {
    //if to delete is head
    if (head == toDelete) {
        head = head->next;

    } else {
        //find node preceding node to delete
        struct node *current = head;
        while (current->next != toDelete) {
            current = current->next;
        }
        current = current->next->next;
    }
    return head;
}

void print(struct node * head) {
    struct node *current = head;

    while (current != (struct node *) 0) {
        printf("%i\n", current->value);
        current = current->next;
    }
}

问题#1:
所以我试着写:
delete(head, node3);

但是xCode希望我在“node3”前面添加“&”。通常,当我定义一个函数来获取指针时,是否需要传递内存地址,这是真的吗?

问题2:

我的打印功能适用于打印出3个节点的值。调用delete并尝试删除node3后,它仍会打印出3个节点。我不确定哪里出了问题。我找到要删除的节点之前的节点,并将其下一个指针设置为之后的节点(非正式地:node.next = node.next.next)。

有任何想法吗?

谢谢您的帮助,
克莱曼

最佳答案



是的,xCode是正确的。 node3struct node,但是您的函数deletestruct node *作为第二个参数,因此您必须将指针传递给node3,而不是变量本身。



这是因为您没有更改next的值。另外,为了确保内存安全,请不要忘记检查指针是否为NULL:

while ((current->next != toDelete) && (current->next != NULL)) {
    current = current->next;
}
if (current->next != NULL)
    current->next = current->next->next;

关于c - C语言的基本链表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30279364/

10-12 16:15