用c++完成一个函数的定义,实现两个有序的环形单向链表的合并,并且合并之后的环形链表仍是有序的
时间: 2024-05-01 13:16:47 浏览: 73
c++两有序单链表的合并算法
5星 · 资源好评率100%
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int val;
struct Node* next;
} Node;
Node* mergeCircularLinkedList(Node* head1, Node* head2) {
if (!head1) return head2;
if (!head2) return head1;
Node* p1 = head1->next;
Node* p2 = head2->next;
Node* newHead = (Node*)malloc(sizeof(Node));
newHead->next = newHead;
Node* p = newHead;
while (p1 != head1 && p2 != head2) {
if (p1->val < p2->val) {
p->next = p1;
p1 = p1->next;
} else {
p->next = p2;
p2 = p2->next;
}
p = p->next;
}
if (p1 == head1) {
p->next = p2;
} else {
p->next = p1;
}
Node* tmp = newHead->next;
free(newHead);
return tmp;
}
int main() {
// construct two circular linked lists
Node* head1 = (Node*)malloc(sizeof(Node));
head1->val = 1;
Node* p1 = head1;
for (int i = 3; i <= 9; i += 2) {
Node* node = (Node*)malloc(sizeof(Node));
node->val = i;
p1->next = node;
p1 = node;
}
p1->next = head1;
Node* head2 = (Node*)malloc(sizeof(Node));
head2->val = 2;
Node* p2 = head2;
for (int i = 4; i <= 10; i += 2) {
Node* node = (Node*)malloc(sizeof(Node));
node->val = i;
p2->next = node;
p2 = node;
}
p2->next = head2;
// merge two circular linked lists
Node* newHead = mergeCircularLinkedList(head1, head2);
// print the merged circular linked list
Node* p = newHead;
do {
printf("%d ", p->val);
p = p->next;
} while (p != newHead);
printf("\n");
// free the memory
p = head1;
do {
Node* tmp = p->next;
free(p);
p = tmp;
} while (p != head1);
p = head2;
do {
Node* tmp = p->next;
free(p);
p = tmp;
} while (p != head2);
p = newHead;
do {
Node* tmp = p->next;
free(p);
p = tmp;
} while (p != newHead);
return 0;
}
```
阅读全文