【问题标题】:Basic Linked List in CC中的基本链表
【发布时间】:2015-07-28 13:12:44
【问题描述】:

我正在用 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 个节点。我不确定我哪里出错了。我找到要删除的节点之前的节点,并将其 next 指针设置为节点之后的节点(非正式地:node.next = node.next.next)。

有什么想法吗?

感谢您的帮助, 布莱曼

【问题讨论】:

  • (1) 是的,pointer 指向某物意味着您需要 地址 某物。 (2) 你的删除函数没有做任何事情:current = current-&gt;next-&gt;next; 只改变一个局部变量。

标签: c linked-list


【解决方案1】:

只需尝试将current = current-&gt;next-&gt;next; 更改为current-&gt;next=current-&gt;next-&gt;next。如果它不起作用,请告诉我。

【讨论】:

    【解决方案2】:

    你应该传递它&amp;node3。要删除,请更改您的代码 current = current-&gt;next-&gt;next;current-&gt;next = current-&gt;next-&gt;next;

    【讨论】:

      【解决方案3】:
      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
      

      【讨论】:

        【解决方案4】:

        一般是不是我定义一个函数取指针的时候,需要传入内存地址?

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

        调用delete并尝试删除node3后,仍然打印出3个节点。

        这是因为您没有更改 next 的值。另外,为了内存安全,别忘了检查指针是否为NULL

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-02-09
          • 1970-01-01
          • 2018-10-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-08
          • 2018-02-17
          相关资源
          最近更新 更多