c - C 中的基本链表

标签 c linked-list

我正在用 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)。

有什么想法吗?

感谢您的帮助, 布莱曼

最佳答案

but xCode wanted me to add "&" in front of "node3". Is it generally true that
when I define a function to take a pointer, I need to pass in the memory 
address?

是的,如果你声明函数接受一个指针,你必须给它传递一个指针。

此外,当从链表中删除一个值时,您将要更改

current->next = current->next->next

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

相关文章:

c - 在 Dev C++ 编译器上,以下代码的输出是 10,10 我无法理解 a 的值是如何分配给 b 的?

java - 如何在java中打乱链表

java - 如何在自定义 OrderedLinkedList 类中显示从列表中删除了哪些元素?

C - 对包含结构类型的结构进行 malloc/free

c++ - 使用前一个节点的地址删除节点

c - 单向链表C反向数据读取

c - 有没有一个示例如何捕获当我用鼠标右键单击任务栏上的图标时的事件?

c - 什么是分隔符?

编译器不会在函数参数不匹配时发出错误/警告

c - 奇怪的 react