利用c语言将两个循环单链表合并为一个循环单链表,且要求空间复杂度为O(1),写出最简单的完整代码
时间: 2023-05-30 21:04:03 浏览: 99
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *merge(Node *head1, Node *head2) {
if (head1 == NULL) return head2;
if (head2 == NULL) return head1;
Node *tail1 = head1->next;
while (tail1->next != head1) tail1 = tail1->next;
tail1->next = head2->next;
free(head2);
return head1;
}
int main() {
Node *head1 = (Node*)malloc(sizeof(Node));
head1->data = 1;
head1->next = (Node*)malloc(sizeof(Node));
head1->next->data = 3;
head1->next->next = (Node*)malloc(sizeof(Node));
head1->next->next->data = 5;
head1->next->next->next = head1;
Node *head2 = (Node*)malloc(sizeof(Node));
head2->data = 2;
head2->next = (Node*)malloc(sizeof(Node));
head2->next->data = 4;
head2->next->next = (Node*)malloc(sizeof(Node));
head2->next->next->data = 6;
head2->next->next->next = head2;
Node *head = merge(head1, head2);
Node *p = head;
do {
printf("%d ", p->data);
p = p->next;
} while (p != head);
printf("\n");
return 0;
}
```
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)