用c语言写两个有序链表序列的交集
时间: 2024-05-13 14:17:51 浏览: 86
以下是用 C 语言实现两个有序链表序列的交集的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
struct ListNode {
int val;
struct ListNode *next;
};
// 创建链表节点
struct ListNode* createNode(int val) {
struct ListNode* node = (struct ListNode*) malloc(sizeof(struct ListNode));
node->val = val;
node->next = NULL;
return node;
}
// 向链表尾部添加元素
void addNode(struct ListNode** head, int val) {
struct ListNode* node = createNode(val);
if (*head == NULL) {
*head = node;
} else {
struct ListNode* curr = *head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = node;
}
}
// 打印链表
void printList(struct ListNode* head) {
struct ListNode* curr = head;
while (curr != NULL) {
printf("%d ", curr->val);
curr = curr->next;
}
printf("\n");
}
// 计算两个有序链表的交集
struct ListNode* getIntersection(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* dummy = createNode(-1);
struct ListNode* curr = dummy;
while (l1 != NULL && l2 != NULL) {
if (l1->val == l2->val) {
addNode(&curr, l1->val);
l1 = l1->next;
l2 = l2->next;
} else if (l1->val < l2->val) {
l1 = l1->next;
} else {
l2 = l2->next;
}
}
return dummy->next;
}
int main() {
// 创建第一个有序链表
struct ListNode* l1 = NULL;
addNode(&l1, 1);
addNode(&l1, 2);
addNode(&l1, 3);
addNode(&l1, 4);
addNode(&l1, 5);
printf("List 1: ");
printList(l1);
// 创建第二个有序链表
struct ListNode* l2 = NULL;
addNode(&l2, 3);
addNode(&l2, 4);
addNode(&l2, 5);
addNode(&l2, 6);
addNode(&l2, 7);
printf("List 2: ");
printList(l2);
// 计算两个有序链表的交集
struct ListNode* intersection = getIntersection(l1, l2);
printf("Intersection: ");
printList(intersection);
return 0;
}
```
输出结果:
```
List 1: 1 2 3 4 5
List 2: 3 4 5 6 7
Intersection: 3 4 5
```
阅读全文