以下是C语言实现查找单链表的某个节点,并返回该节点的前继指针的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *find_previous(Node *head, Node *target) {
Node *previous = NULL;
Node *current = head;
while (current != NULL && current != target) {
previous = current;
current = current->next;
}
return previous;
}
int main() {
Node *head = NULL;
Node *node1 = (Node *)malloc(sizeof(Node));
Node *node2 = (Node *)malloc(sizeof(Node));
Node *node3 = (Node *)malloc(sizeof(Node));
node1->data = 1;
node2->data = 2;
node3->data = 3;
node1->next = node2;
node2->next = node3;
node3->next = NULL;
head = node1;
Node *target = node2;
Node *previous = find_previous(head, target);
if (previous == NULL) {
printf("Target node is the head of the list.\n");
} else {
printf("The previous node of the target node is %d.\n", previous->data);
}
return 0;
}
在这个例子中,我们定义了一个Node结构体,包含一个整数data和一个指向下一个节点的指针next。我们还定义了一个find_previous函数,它接受一个指向链表头节点的指针head和一个指向目标节点的指针target,并返回目标节点的前继节点的指针。在find_previous函数中,我们使用了一个while循环来遍历链表,直到找到目标节点或者到达链表末尾。在循环中,我们使用previous指针来记录当前节点的前继节点,然后将current指针移动到下一个节点。最后,我们返回previous指针,它指向目标节点的前继节点。
在main函数中,我们创建了一个包含三个节点的链表,并将其头节点指针赋值给head变量。然后,我们定义了一个指向目标节点的指针target,它指向第二个节点。我们调用find_previous函数来查找目标节点的前继节点,并将返回的指针赋值给previous变量。最后,我们根据previous指针是否为NULL来判断目标节点是否为链表头节点,并输出结果。