用C语言来写一个如何判断两个链表是否相交的程序
时间: 2024-05-25 12:16:06 浏览: 114
编程判断两个链表是否相交
以下是一个用C语言编写的判断两个链表是否相交的程序:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
int isIntersect(Node* list1, Node* list2) {
Node* p1 = list1;
Node* p2 = list2;
while (p1 != NULL) {
p2 = list2;
while (p2 != NULL) {
if (p1 == p2) {
return 1;
}
p2 = p2->next;
}
p1 = p1->next;
}
return 0;
}
int main() {
// 创建两个链表
Node* list1 = NULL;
Node* list2 = NULL;
for (int i = 1; i <= 5; i++) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = i;
newNode->next = NULL;
if (list1 == NULL) {
list1 = newNode;
} else {
newNode->next = list1;
list1 = newNode;
}
}
for (int i = 6; i <= 10; i++) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = i;
newNode->next = NULL;
if (list2 == NULL) {
list2 = newNode;
} else {
newNode->next = list2;
list2 = newNode;
}
}
// 将两个链表相交
Node* p = list1;
while (p->next != NULL) {
p = p->next;
}
p->next = list2->next->next;
// 判断两个链表是否相交
if (isIntersect(list1, list2)) {
printf("两个链表相交\n");
} else {
printf("两个链表不相交\n");
}
return 0;
}
阅读全文