两个有序链表序列的交集 C语言
时间: 2023-07-11 12:31:53 浏览: 139
两个有序链表序列的合并_C语言_
5星 · 资源好评率100%
以下是C语言的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
typedef struct ListNode ListNode;
struct ListNode *getIntersectionNode(struct ListNode *head1, struct ListNode *head2) {
ListNode* p1 = head1, *p2 = head2;
ListNode* head = (ListNode*)malloc(sizeof(ListNode)); // 创建一个虚拟头节点
ListNode* tail = head; // tail指向新链表的尾节点
while (p1 && p2) {
if (p1->val < p2->val) {
p1 = p1->next;
} else if (p1->val > p2->val) {
p2 = p2->next;
} else {
tail->next = (ListNode*)malloc(sizeof(ListNode));
tail->next->val = p1->val;
tail = tail->next;
p1 = p1->next;
p2 = p2->next;
}
}
tail->next = NULL; // 将新链表的尾节点指向NULL,表示结束
return head->next; // 返回新链表的头节点
}
int main() {
ListNode* head1 = (ListNode*)malloc(sizeof(ListNode));
head1->val = 1;
head1->next = (ListNode*)malloc(sizeof(ListNode));
head1->next->val = 2;
head1->next->next = (ListNode*)malloc(sizeof(ListNode));
head1->next->next->val = 3;
head1->next->next->next = (ListNode*)malloc(sizeof(ListNode));
head1->next->next->next->val = 4;
head1->next->next->next->next = NULL;
ListNode* head2 = (ListNode*)malloc(sizeof(ListNode));
head2->val = 2;
head2->next = (ListNode*)malloc(sizeof(ListNode));
head2->next->val = 4;
head2->next->next = NULL;
ListNode* head = getIntersectionNode(head1, head2);
while (head) {
printf("%d ", head->val);
head = head->next;
}
return 0;
}
```
在这个实现中,我们同样使用了一个虚拟头节点来简化代码,使用了动态内存分配来创建节点,需要在程序结束时手动释放申请的空间。
阅读全文