c语言有序链表的交集
时间: 2024-04-12 20:21:53 浏览: 86
数据结构习题答案
5星 · 资源好评率100%
要实现有序链表的交集,可以先遍历两个链表,将它们的共同元素放入一个新的链表中。具体实现可以使用双指针,分别指向两个链表的头节点,比较节点的值,如果相等则将该节点加入新链表中,否则将值较小的节点向后移动一位。直到其中一个链表遍历完毕。
以下是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* createList(int* nums, int numsSize) {
struct ListNode* head = NULL;
struct ListNode* tail = NULL;
for (int i = 0; i < numsSize; i++) {
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = nums[i];
node->next = NULL;
if (head == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
struct ListNode* getIntersectionNode(struct ListNode* headA, struct ListNode* headB) {
struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode));
dummy->next = NULL;
struct ListNode* tail = dummy;
while (headA != NULL && headB != NULL) {
if (headA->val == headB->val) {
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = headA->val;
node->next = NULL;
tail->next = node;
tail = node;
headA = headA->next;
headB = headB->next;
} else if (headA->val < headB->val) {
headA = headA->next;
} else {
headB = headB->next;
}
}
return dummy->next;
}
void printList(struct ListNode* head) {
while (head != NULL) {
printf("%d ", head->val);
head = head->next;
}
printf("\n");
}
int main() {
int nums1[] = {1, 2, 3, 4, 5};
int nums2[] = {2, 4, 6};
struct ListNode* head1 = createList(nums1, 5);
struct ListNode* head2 = createList(nums2, 3);
struct ListNode* intersection = getIntersectionNode(head1, head2);
printList(intersection); // 输出 2 4
return 0;
}
```
阅读全文