有序链表的插入要先依次比较要插入的值和链表中各个值的大小
因为链表一开始有序,所以当链表中的数大于要插入的数时,我们就找到了插入的位置,但是此时我们要在找到的节点前面插入数据,由于是单链表,前面的节点会丢失,所以要再创一个指针指着前面的那个节点,然后用尾插法插入即可。
但要注意特殊情况,如果要插入的值比链表中的所有值都要大时,要有特殊的处理操作
具体代码段如下:
#include <iostream>
#include <stdlib.h>
using namespace std;
#define OK 1
#define ERROR 0
#define NO -1
typedef int ElemType;
typedef int status;
typedef struct Listnode{
ElemType elem;
struct Listnode *next;
}Listnode,*LNode;
status chuanglist(LNode &L);//链表初始化
status shulist(LNode &L,int n);//输入初始链表的值
status chulist(LNode L);//输出链表的值
status youxuchalist(LNode &L,ElemType e);//插入操作
int main()
{
int n,a;//n为要输入值的个数,a为要插入的值
LNode L;//L链表
cout<<"请输入想要输入的值的个数:";
cin>>n;
chuanglist(L);
cout<<"请输入一组有序的数:";
shulist(L,n);
cout<<"您输入的数为:";
chulist(L);
cout<<endl;
cout<<"请输入想要插入的值:";
cin>>a;
youxuchalist(L,a);
cout<<"插入完后为:";
chulist(L);
cout<<endl;
}
status chuanglist(LNode &L)
{
L=new Listnode;
if(L==NULL)
return ERROR;
L->next=NULL;
return OK;
}
status shulist(LNode &L,int n)
{
int i;
LNode p,q;
p=L;
for(i=0;i<n;i++)
{
q=new Listnode;
cin>>q->elem;
p->next=q;
q->next=NULL;
p=q;
}
return OK;
}
status chulist(LNode L)
{
LNode p;
p=L->next;
while(p!=NULL)
{
cout<<p->elem<<" ";
p=p->next;
}
return OK;
}
status youxuchalist(LNode &L,ElemType e)
{
LNode p,r,q;//p节点中的数比要插入的数小时,此时,r节点是要插入的前一个节点
p=L->next;
r=L;
while(p)
{
if(p->elem>e)
{
q=new Listnode;
q->elem=e;
q->next=r->next;
r->next=q;
break;
}
p=p->next;
r=r->next;
}
if(!p)//如果要插的数是最大的数,上一个while循环就会退出,所以要加以下的操作将最大的那个数插入链表
{
q=new Listnode;
q->elem=e;
q->next=r->next;
r->next=q;
}
return OK;
}