链表暴力解-判断一个链表B是否是链表A的子序列

文章讲述了如何使用C语言实现一个函数isSubsequence,判断链表B是否为链表A的子序列,通过遍历和比较节点数据来确定。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <stdlib.h>

// 链表节点的结构体定义
struct Node {
    int data;
    struct Node* next;
};

// 判断链表B是否是链表A的子序列
int isSubsequence(struct Node* A, struct Node* B) {
    struct Node* p = A;
    struct Node* q = B;

    while (p != NULL) {
        struct Node* r = p;

        while (q != NULL && r != NULL && q->data == r->data) {
            q = q->next;
            r = r->next;
        }

        if (q == NULL) {
            return 1;  // 链表B是链表A的子序列
        } else {
            q = B;
            p = p->next;
        }
    }

    return 0;  // 链表B不是链表A的子序列
}

// 创建链表节点
struct Node* createNode(int data) {
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

// 主函数
int main() {
    // 创建链表A: 1 -> 2 -> 3 -> 4 -> 5
    struct Node* A = createNode(1);
    A->next = createNode(2);
    A->next->next = createNode(3);
    A->next->next->next = createNode(4);
    A->next->next->next->next = createNode(5);

    // 创建链表B: 2 -> 3 -> 4
    struct Node* B = createNode(2);
    B->next = createNode(3);
    B->next->next = createNode(4);

    // 判断链表B是否是链表A的子序列
    if (isSubsequence(A, B)) {
        printf("链表B是链表A的子序列\n");
    } else {
        printf("链表B不是链表A的子序列\n");
    }

    // 释放内存
    free(A);
    free(B);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值