u012455213 于 2013.10.15 21:44 提问

``````#include <stdio.h>
#include <stdlib.h>
``````

#define LIST_INIT_SIZE 100 //线性表储存空间的初始分配
#define LISTINCREMENT 10 //线性表储存空间的分配增量
#define WantAmount 5
#define TRUE 1
#define FALSE 0
#define ERROR 0
#define OK 1
#define OVERFLOW -2
#define INFEASIBLE -1
typedef int ElemType;
typedef int Status;

typedef struct{
ElemType *elem;
int length;
int listsize;
}SqList;

Status ListEmpty(SqList L) //判空
{
if(L.length<=0) return TRUE;
else return ERROR;
}

Status InitList_Sq(SqList L){ //初始化initial
L->elem=(ElemType
)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if(!L->elem) exit(OVERFLOW);
L->length=0;
L->listsize=LIST_INIT_SIZE;
return OK;
}

int Find(SqList L,ElemType n) //查找
{
int pos=0;
if(ListEmpty(L))
{
printf("顺序表为空，找不到");
return ERROR;
}
while(pos<L.length&&L.elem[pos]!=n)pos++;
if(pos<L.length) return pos+1;
else return ERROR ;
}

Status ListInsert_Sq(SqList *L,int i,ElemType e)
//在顺序线性表L中第i个位置之前插入新的元素e
{ ElemType *newbase;
ElemType *p;
ElemType *q;

``````if(i<1||i>L->length+1)return ERROR;//i值不合法
if(L->length>=L->listsize)      //当前存储空间已满，增加分配
{
newbase=(ElemType *)realloc(L->elem,
(LISTINCREMENT+L->listsize)*sizeof(ElemType));
if(!newbase)exit(OVERFLOW)  ;    //存储分配失败
L->elem=newbase;            //新基址
L->listsize+=LISTINCREMENT ; //增加存储容量
}

q=&(L->elem[i-1]);                  //q为插入位置
for(p=&(L->elem[L->length-1]);p>=q;--p)*(p+1)=*p;
//元素右移

*q=e;           //插入e
++L->length;
return OK;
``````

}

Status GIVEBIRTH(SqList *L)
{ int i,x;
for(i=0;i<WantAmount;i++)
{
scanf("%d",&x);
ListInsert_Sq(L,i+1,x);

``````}
return OK;
``````

}

Status DisplayList(SqList M)
{
int i;
for(i=0;i<WantAmount;i++)
{
printf("%d\t",M.elem[i]);
}
printf("\n");
return OK;

}

Status FindIt(SqList L)
{ int w,x;
printf("find the position of-");
scanf("%d\n",&x);
w=Find(L,x);
printf("the location of %d is %d",x,w);
//这句话为什么要在按下除ENTER外的任意键才出现?!?!
return OK;

}

void main(){

`````` SqList L;
InitList_Sq(&L);
printf("请输入%d个数：\n",WantAmount);
GIVEBIRTH(&L);
DisplayList(L);

FindIt(L);

getch();
``````

}

1个回答

shen_wei      2015.10.14 13:44

scanf("%d\n",&x); 这个需要回车才能接受当前的输入数据。
w=Find(L,x);
printf("the location of %d is %d",x,w);
//这句话为什么要在按下除ENTER外的任意键才出现?!?!