BUPT-homework/semester2/pset2/3-subLinkedList.c

100 lines
1.5 KiB
C
Raw Permalink Normal View History

2022-03-21 18:00:27 +08:00
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *constructLinkedList();
Node *appendLinkedList(Node *ptr, int data);
void deleteLinkedList(Node *head);
int main(void) {
Node *listA = constructLinkedList();
Node *listB = constructLinkedList();
Node *ptrA = listA, *ptrB, *ptrC;
int matched = 0;
while (ptrA != NULL) {
matched = 0;
ptrB = listB;
if (ptrA->data == ptrB->data) {
matched = 1;
ptrC = ptrA;
while (ptrB != NULL) {
if (ptrC == NULL) {
matched = 0;
break;
}
if (ptrC->data != ptrB->data) {
matched = 0;
break;
}
ptrB = ptrB->next;
ptrC = ptrC->next;
}
}
if (matched == 1) {
break;
}
ptrA = ptrA->next;
}
if (matched) {
printf("ListB is the sub sequence of ListA.");
} else {
printf("ListB is not the sub sequence of ListA.");
}
deleteLinkedList(listA);
deleteLinkedList(listB);
return 0;
}
Node *constructLinkedList() {
Node *head = malloc(sizeof(struct Node));
int buf;
scanf("%d", &buf);
head->data = buf;
head->next = NULL;
Node *ptr = head;
scanf("%d", &buf);
while (buf != -1) {
ptr = appendLinkedList(ptr, buf);
scanf("%d", &buf);
}
return head;
}
Node *appendLinkedList(Node *ptr, int data) {
Node *new = malloc(sizeof(Node));
new->data = data;
new->next = NULL;
ptr->next = new;
return new;
}
void deleteLinkedList(Node *head) {
if (head == NULL) {
return;
} else {
deleteLinkedList(head->next);
free(head);
}
}