编写c语言程序,建立2个带头结点单链表,输入若干整数将正整数插入第1个单链表,将负整数插入第2个单链表,插入前和插入后单链表保持递增或相等次序,显示2个单链表,最后销毁。程序不可存在内存泄漏。
时间: 2024-03-23 21:18:00 浏览: 20
C语言实现单向链表的创建、插入,删除节点,和2个链表合并
5星 · 资源好评率100%
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* createList() {
Node* head = (Node*)malloc(sizeof(Node));
head->next = NULL;
return head;
}
void insert(Node* head, int data) {
Node* p = head;
while (p->next && p->next->data < data) {
p = p->next;
}
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = p->next;
p->next = node;
}
void printList(Node* head) {
Node* p = head->next;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void destroyList(Node* head) {
Node* p = head;
while (p) {
Node* q = p->next;
free(p);
p = q;
}
}
int main() {
Node* positiveList = createList();
Node* negativeList = createList();
int data;
while (scanf("%d", &data) != EOF) {
if (data > 0) {
insert(positiveList, data);
} else {
insert(negativeList, data);
}
}
printf("Positive list: ");
printList(positiveList);
printf("Negative list: ");
printList(negativeList);
destroyList(positiveList);
destroyList(negativeList);
return 0;
}
```
阅读全文