已知两个非降序链表序列S1与S2,设计函数构造出S1与S2的交集新链表S3。c++代码
时间: 2024-03-16 15:18:42 浏览: 63
C++实现合并两个排序的链表
5星 · 资源好评率100%
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode {
int val;
struct ListNode *next;
} ListNode;
ListNode* createList(int arr[], int n) {
if (n == 0) {
return NULL;
}
ListNode *head = (ListNode*)malloc(sizeof(ListNode));
head->val = arr[0];
head->next = NULL;
ListNode *p = head;
for (int i = 1; i < n; i++) {
p->next = (ListNode*)malloc(sizeof(ListNode));
p->next->val = arr[i];
p->next->next = NULL;
p = p->next;
}
return head;
}
void printList(ListNode *head) {
if (head == NULL) {
printf("NULL\n");
return;
}
while (head != NULL) {
printf("%d->", head->val);
head = head->next;
}
printf("NULL\n");
}
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
if (headA == NULL || headB == NULL) {
return NULL;
}
ListNode *p1 = headA;
ListNode *p2 = headB;
while (p1 != p2) {
p1 = (p1 == NULL ? headB : p1->next);
p2 = (p2 == NULL ? headA : p2->next);
}
return p1;
}
int main() {
int arr1[] = {1, 2, 3, 4, 7};
int arr2[] = {2, 4, 6, 7, 8};
ListNode *head1 = createList(arr1, 5);
ListNode *head2 = createList(arr2, 5);
printf("List 1: ");
printList(head1);
printf("List 2: ");
printList(head2);
printf("Intersection: ");
printList(getIntersectionNode(head1, head2));
return 0;
}
```
阅读全文