7-1 有序链表的插入(20 分)
已知一个递增有序链表L(带头结点,元素为整数),编写程序将一个新整数插入到L中,并保持L的有序性。 其中单链表的类型定义参考如下:
typedef int elementType;
typedef struct lnode
{ elementType data;
struct lnode *next;
}Lnode,* LinkList;
输入格式:
输入分三行
第一行 元素个数
第二行 元素的值,元素间用空格分隔。
第三行 待插入的元素值
输出格式:
在一行中输出有序链表元素值,每个元素前输出一个空格以便与相邻元素分隔。
输入样例:
5
1 3 5 7 9
4
输出样例:
1 3 4 5 7 9
#include<cstdio>
#include<cstring>
#include<iostream>
#include<stack>
#include<set>
#include<map>
#include<queue>
#include<cmath>
#include<iomanip>
#include<algorithm>
using namespace std;
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -1
typedef int ElemType;
typedef struct LNode{
ElemType data;
struct LNode *next;
}LNode,*LinkList;
int ListInit(LinkList &L,int n)
{
LNode *cur,*rea;
LNode *head=(LNode*)malloc(sizeof(LNode));
L=head;
if(!head) exit(OVERFLOW);
head->next=NULL;
cur=head;
rea=head;
for(int i=0;i<n;i++){
int m;
scanf("%d",&m);
cur=(LNode*)malloc(sizeof(LNode));
if(!cur) exit(OVERFLOW);
cur->data=m;
rea->next=cur;
rea=cur;
}
rea->next=NULL;
return OK;
}
int List_insert(LinkList &L,int n)
{
LNode *tmp,*cur,*rea;
cur=L->next;
rea=L;
tmp=(LNode*)malloc(sizeof(LNode));
if(!tmp) exit(OVERFLOW);
tmp->next=NULL;
tmp->data=n;
if(!rea->next){
rea->next=tmp;
return OK;
}
while(cur){
if(cur->data>=n){
tmp->next=cur;
rea->next=tmp;
return OK;
}
rea=cur;
cur=cur->next;
}
tmp->next=cur;
rea->next=tmp;
return OK;
}
void print_List(LinkList &L)
{
LNode *cur;
cur=L->next;
int k=0;
while(cur){
if(k){
printf(" %d",cur->data);
cur=cur->next;
k++;
}
else{
printf("%d",cur->data);
cur=cur->next;
k++;
}
}
printf("\n");
}
int main()
{
int n;
scanf("%d",&n);
LNode *L;
ListInit(L,n);
int m;
scanf("%d",&m);
List_insert(L,m);
print_List(L);
}