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