查找单链表的某个节点,并返回该节点的前继指针

以下是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来判断目标节点是否为链表头节点,并输出结果。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值