编写程序,建立2个带头结点单链表,输入若干整数将正整数插入第1个单链表,将负整数插入第2个单链表,插入前和插入后单链表保持递增或相等次序,显示2个单链表,最后销毁。程序不可存在内存泄漏。
时间: 2024-03-23 18:25:25 浏览: 44
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
void insert(Node *head, int data) {
Node *p = head;
while (p->next != NULL && p->next->data < data) {
p = p->next;
}
Node *new_node = (Node *)malloc(sizeof(Node));
new_node->data = data;
new_node->next = p->next;
p->next = new_node;
}
void print_list(Node *head) {
Node *p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void destroy_list(Node *head) {
Node *p = head;
while (p != NULL) {
Node *temp = p;
p = p->next;
free(temp);
}
}
int main() {
Node *positive_head = (Node *)malloc(sizeof(Node));
positive_head->next = NULL;
Node *negative_head = (Node *)malloc(sizeof(Node));
negative_head->next = NULL;
int data;
while (scanf("%d", &data) != EOF) {
if (data > 0) {
insert(positive_head, data);
} else if (data < 0) {
insert(negative_head, data);
}
}
print_list(positive_head);
print_list(negative_head);
destroy_list(positive_head);
destroy_list(negative_head);
return 0;
}
阅读全文
相关推荐















