#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;
}