请你编写程序,建立2个带头结点单链表,输入若干整数将正整数插入第1个单链表,将负整数插入第2个单链表,插入前和插入后单链表保持递增或相等次序,显示2个单链表,最后销毁。程序不可存在内存泄漏。
时间: 2024-03-23 09:17:54 浏览: 76
好的,这是一道关于链表的编程题目。我们可以先定义一个结构体来表示链表节点:
```c
typedef struct ListNode {
int val;
struct ListNode* next;
} ListNode;
```
然后我们可以定义两个头结点,分别表示正整数链表和负整数链表:
```c
ListNode* positiveHead = (ListNode*)malloc(sizeof(ListNode));
ListNode* negativeHead = (ListNode*)malloc(sizeof(ListNode));
positiveHead->next = NULL;
negativeHead->next = NULL;
```
接下来,我们可以循环输入整数,并根据正负情况插入到对应的链表中:
```c
int num;
while (scanf("%d", &num) != EOF) {
ListNode* node = (ListNode*)malloc(sizeof(ListNode));
node->val = num;
node->next = NULL;
if (num >= 0) {
ListNode* p = positiveHead;
while (p->next && p->next->val < num) {
p = p->next;
}
node->next = p->next;
p->next = node;
} else {
ListNode* p = negativeHead;
while (p->next && p->next->val < num) {
p = p->next;
}
node->next = p->next;
p->next = node;
}
}
```
最后,我们可以循环输出两个链表:
```c
ListNode* p = positiveHead->next;
while (p) {
printf("%d ", p->val);
ListNode* tmp = p;
p = p->next;
free(tmp);
}
printf("\n");
ListNode* q = negativeHead->next;
while (q) {
printf("%d ", q->val);
ListNode* tmp = q;
q = q->next;
free(tmp);
}
```
完整代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode {
int val;
struct ListNode* next;
} ListNode;
int main() {
ListNode* positiveHead = (ListNode*)malloc(sizeof(ListNode));
ListNode* negativeHead = (ListNode*)malloc(sizeof(ListNode));
positiveHead->next = NULL;
negativeHead->next = NULL;
int num;
while (scanf("%d", &num) != EOF) {
ListNode* node = (ListNode*)malloc(sizeof(ListNode));
node->val = num;
node->next = NULL;
if (num >= 0) {
ListNode* p = positiveHead;
while (p->next && p->next->val < num) {
p = p->next;
}
node->next = p->next;
p->next = node;
} else {
ListNode* p = negativeHead;
while (p->next && p->next->val < num) {
p = p->next;
}
node->next = p->next;
p->next = node;
}
}
ListNode* p = positiveHead->next;
while (p) {
printf("%d ", p->val);
ListNode* tmp = p;
p = p->next;
free(tmp);
}
printf("\n");
ListNode* q = negativeHead->next;
while (q) {
printf("%d ", q->val);
ListNode* tmp = q;
q = q->next;
free(tmp);
}
return 0;
}
```
希望能够帮到你!
阅读全文