已知一个递增有序链表L(带头结点,元素为整数),编写程序将一个新整数插入到L中,并保持L的有序
输入:
输入分三行
第一行 元素个数
第二行 元素的值,元素间用空格分隔。
第三行 待插入的元素值
输出:开头有空格
Code:
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
//函数状态码定义
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int statue;
typedef int ElemType;
typedef struct LNode
{
ElemType data;
LNode * next;
};
typedef LNode* LinkList;
statue ListCreate_L(LinkList & L, ElemType n) //原表的引用,要插入的初始化插入的元素的个数
{
LNode *curPtr, *reaPtr;
L = (LNode*) malloc(sizeof(LNode));
if(!L)exit(OVERFLOW);
L->next = NULL; //一定要先开辟空间然后在进行操作,不然就会崩掉
if(n == 0) return OK;
curPtr = L->next; reaPtr = L;
while(n--)
{
curPtr = (LNode*)malloc(sizeof(LNode));
if(!curPtr)exit(OVERFLOW);
scanf("%d", &curPtr->data);
reaPtr->next = curPtr;
reaPtr = curPtr;
}
curPtr->next = NULL;
return OK;
}
//下面是需要实现的函数的声明
void Listinsert_L(LinkList &L, ElemType x)
{
LNode *reaPtr, *curPtr;
curPtr = L->next; reaPtr = L;
LNode *in;
in = (LNode*)malloc(sizeof(LNode));
in->data = x;
bool flag = false;
while(curPtr != NULL)
{
if((curPtr->data) > x) //原来就是有序的,直接找到第一个比所要插入的元素大的位置
{
reaPtr->next = in; //修改前驱
in->next = curPtr; //所插入节点的后继修改
flag = true; //不是插在最后一个位置
return ;
}
reaPtr = curPtr;
curPtr = curPtr->next;
}
if(!flag)
{
reaPtr->next = in;
in->next = NULL;
}
return ;
}
void List_print_L(LinkList L)
{
LNode *p;
p = L->next;
while(p != NULL)
{
printf(" %d", p->data);
p = p->next;
}
return ;
}
int main()
{
LinkList L;
int n;
int x,k;
scanf("%d",&n); //输入链表中元素个数
ListCreate_L(L,n); //创建一个容量大小为n的链表
scanf("%d",&x); //输入待插入元素
Listinsert_L(L, x);
List_print_L(L);
return 0;
}