详细请看代码
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef struct node{
int va;
struct node *next;
}Node, *LNode;
int main(){
LNode p, q, l, L1, L2;
int k, i, n, jk[100];
cin >> n;
L1 = (LNode)malloc(sizeof(Node));
L2 = (LNode)malloc(sizeof(Node));
for(i = 1; i <= n; ++i)
scanf("%d", &jk[i]);
L1->next = NULL;
for(i = 1; i <= n; ++i){ //头插
p = (LNode)malloc(sizeof(Node));
p->va = jk[i];
p->next = L1->next;
L1->next = p;
}
q = L2;
for(i = 1; i <= n; ++i){ //尾插
l = (LNode)malloc(sizeof(Node));
l->va = jk[i];
q->next = l;
q = l;
}
q->next = NULL;
printf("Head Insert:\n");
p = L1->next;
while(p != NULL) {
printf("%d ", p->va);
p = p->next;
}
printf("\nBehind Insert:\n");
p = L2->next;
while(p != NULL) {
printf("%d ", p->va);
p = p->next;
}
cout << endl;
while(cin >> k && k){
q = L2;
while(q->next != NULL && q->next->va < k) q = q->next;
l = (LNode)malloc(sizeof(Node));
l->va = k;
l->next = q->next;
q->next = l;
}
p = L2->next;
while(p != NULL) {
printf("%d ", p->va);
p = p->next;
}
q = L1; //销毁
p = L1->next;
while(p != NULL){
free(q);
q = p;
p = p->next;
}
free(q);
q = L2;
p = L2->next;
while(p != NULL){
free(q);
q = p;
p = p->next;
}
free(q);
return 0;
}