C语言中的基本链表
我正在用C写一个基本的链表程序,在删除时遇到了一些麻烦。以下是我所拥有的:C语言中的基本链表,c,linked-list,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 *
#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;
}
}
但是xCode希望我在“node3”前面加上“&”。当我定义一个函数来获取指针时,我需要传入内存地址,这通常是真的吗
问题2:
我的打印功能用于打印3个节点的值。在调用delete并尝试删除node3之后,它仍然会打印出3个节点。我不确定哪里出了错。我找到要删除的节点之前的节点,并将其下一个指针设置为节点之后的节点(非正式地说:node.next=node.next.next)
有什么想法吗
谢谢你的帮助,
b外行只要试着改变
current=current->next->next代码>到current->next=current->next->next
。如果它不起作用,请告诉我。您应该传递它&node3
。若要删除,请从更改您的代码
current=current->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
当我定义一个函数来获取指针时,我需要传入内存地址,这通常是真的吗
是的,xCode是对的node3
是一个struct节点
,但是您的函数delete
将struct节点*
作为第二个参数,因此您必须将指针传递到node3
,而不是变量本身
在调用delete并尝试删除node3之后,它仍然会打印出3个节点
这是因为您没有更改next
的值。另外,为了内存安全,不要忘记检查指针是否为空:
while ((current->next != toDelete) && (current->next != NULL)) {
current = current->next;
}
if (current->next != NULL)
current->next = current->next->next;
(1) 是的,指向某物的指针意味着你需要某物的地址。(2) 您的删除函数不做任何操作:current=current->next->next代码>仅更改局部变量。
while ((current->next != toDelete) && (current->next != NULL)) {
current = current->next;
}
if (current->next != NULL)
current->next = current->next->next;