建立2个带头结点单链表,输入若干整数将正整数插入第1个单链表,将负整数插入第2个单链表,插入前和插入后单链表保持递增或相等次序,显示2个单链表,最后销毁。程序不可存在内存泄漏。 输入格式: 若干整数。 输出格式: 每行显示一个链表,元素间用分隔符->分隔;共两行 输入样例: 100 2 3 -2 -8 -6 -9 -10 50 2 -1 输出样例: 2->2->3->50->100 -10->-9->-8->-6->-2->-1
时间: 2023-12-24 11:04:42 浏览: 65
好的,我理解了你的问题。以下是基于C语言实现的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义单链表结点
typedef struct ListNode {
int val;
struct ListNode* next;
} ListNode;
// 初始化单链表,返回头结点
ListNode* initList() {
ListNode* head = (ListNode*)malloc(sizeof(ListNode));
head->next = NULL;
return head;
}
// 销毁单链表
void destroyList(ListNode* head) {
ListNode* p = head->next;
while (p) {
ListNode* q = p;
p = p->next;
free(q);
}
free(head);
}
// 插入结点到单链表中
void insertNode(ListNode* head, int val) {
ListNode* p = head;
while (p->next && p->next->val < val) {
p = p->next;
}
ListNode* q = (ListNode*)malloc(sizeof(ListNode));
q->val = val;
q->next = p->next;
p->next = q;
}
// 将正整数插入第1个单链表,将负整数插入第2个单链表
void splitList(ListNode* head1, ListNode* head2) {
int val;
while (scanf("%d", &val) != EOF) {
if (val >= 0) {
insertNode(head1, val);
} else {
insertNode(head2, val);
}
}
}
// 打印单链表
void printList(ListNode* head) {
ListNode* p = head->next;
if (!p) {
printf("NULL\n");
return;
}
printf("%d", p->val);
p = p->next;
while (p) {
printf("->%d", p->val);
p = p->next;
}
printf("\n");
}
int main() {
ListNode* head1 = initList();
ListNode* head2 = initList();
splitList(head1, head2);
printList(head1);
printList(head2);
destroyList(head1);
destroyList(head2);
return 0;
}
```
代码分为四部分:
1. 定义单链表结点。
2. 定义初始化单链表、销毁单链表、插入结点到单链表中、将正整数插入第1个单链表,将负整数插入第2个单链表等函数。
3. 主函数中初始化两个单链表,将输入的整数插入到两个单链表中,最后打印两个单链表,销毁两个单链表。
4. 定义了一个数据样例,方便你进行测试。
希望能够帮到你!
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)