用c语言编写程序,建立2个带头结点单链表,输入若干整数将正整数插入第1个单链表,将负整数插入第2个单链表,插入前和插入后单链表保持递增或相等次序,显示2个单链表,最后销毁。程序不可存在内存泄漏
时间: 2024-03-23 17:13:27 浏览: 39
单链表.c(单链表,使用C语言编写,具有插入、删除、显示等功能)
4星 · 用户满意度95%
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int val;
struct Node *next;
} Node;
Node* createList() {
Node *head = (Node*) malloc(sizeof(Node));
head->next = NULL;
return head;
}
void insert(Node *head, int val) {
Node *p = head;
while (p->next != NULL && p->next->val < val) {
p = p->next;
}
Node *newNode = (Node*) malloc(sizeof(Node));
newNode->val = val;
newNode->next = p->next;
p->next = newNode;
}
void printList(Node *head) {
Node *p = head->next;
while (p != NULL) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
}
void destroyList(Node *head) {
Node *p = head;
while (p != NULL) {
Node *q = p->next;
free(p);
p = q;
}
}
int main() {
Node *list1 = createList();
Node *list2 = createList();
int n, val;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &val);
if (val > 0) {
insert(list1, val);
} else {
insert(list2, val);
}
}
printList(list1);
printList(list2);
destroyList(list1);
destroyList(list2);
return 0;
}
```
阅读全文