思路是,如果l2中存在,就放到一个新链表中,但是怎么都跑不出来
代码呢?
我可以给你写出这段代码,但是我猜测你没有跑通的原因很大可能原因是指针的问题,可能指针指错了或者其他原因等等,初学者很容易在指针这里出现问题。
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode* next;
};
typedef struct ListNode ListNode;
// 遍历链表
void traverseList(ListNode* head) {
ListNode* p = head;
while (p != NULL) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
}
// 创建链表(尾插法)
ListNode* createList(int* nums, int numsSize) {
ListNode* head = NULL;
ListNode* tail = NULL;
for (int i = 0; i < numsSize; i++) {
ListNode* node = (ListNode*)malloc(sizeof(ListNode));
node->val = nums[i];
node->next = NULL;
if (head == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
// 求两个集合的交集
ListNode* getIntersection(ListNode* head1, ListNode* head2) {
ListNode* p1 = head1;
ListNode* p2 = head2;
ListNode* dummy = (ListNode*)malloc(sizeof(ListNode));
ListNode* tail = dummy;
while (p1 != NULL && p2 != NULL) {
if (p1->val == p2->val) {
ListNode* node = (ListNode*)malloc(sizeof(ListNode));
node->val = p1->val;
node->next = NULL;
tail->next = node;
tail = node;
p1 = p1->next;
p2 = p2->next;
} else if (p1->val < p2->val) {
p1 = p1->next;
} else {
p2 = p2->next;
}
}
ListNode* head = dummy->next;
free(dummy);
return head;
}
int main() {
int nums1[] = {1, 2, 3, 4};
int nums2[] = {2, 4, 6};
int numsSize1 = sizeof(nums1) / sizeof(nums1[0]);
int numsSize2 = sizeof(nums2) / sizeof(nums2[0]);
ListNode* head1 = createList(nums1, numsSize1);
ListNode* head2 = createList(nums2, numsSize2);
printf("List 1: ");
traverseList(head1);
printf("List 2: ");
traverseList(head2);
ListNode* intersection = getIntersection(head1, head2);
printf("Intersection: ");
traverseList(intersection);
return 0;
}
思路应该是先排序,然后再比较,否则你每次都要拿一个元素和另一个链表全部比较一次