1.1编写程序,建立2个带头结点单链表,输入若干整数将正整数插入第1个单链表,将负整数插入第2个单链表,插入前和插入后单链表保持递增或相等次序,显示2个单链表,最后销毁。程序不可存在内存泄漏。
时间: 2024-03-23 15:26:00 浏览: 67
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int data;
struct Node *next;
}Node, *LinkedList;
void initList(LinkedList *L){
*L = (LinkedList)malloc(sizeof(Node));
(*L)->next = NULL;
}
void insertElem(LinkedList L, int elem){
Node *p = L;
while(p->next && p->next->data <= elem){
p = p->next;
}
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = elem;
newNode->next = p->next;
p->next = newNode;
}
void showList(LinkedList L){
Node *p = L->next;
while(p){
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void destroyList(LinkedList *L){
Node *p = *L;
while(p){
Node *q = p;
p = p->next;
free(q);
}
*L = NULL;
}
int main(){
LinkedList L1, L2;
initList(&L1);
initList(&L2);
int n;
scanf("%d", &n);
while(n--){
int elem;
scanf("%d", &elem);
if(elem >= 0){
insertElem(L1, elem);
}else{
insertElem(L2, elem);
}
}
showList(L1);
showList(L2);
destroyList(&L1);
destroyList(&L2);
return 0;
}
阅读全文