# 数据结构 线性表 顺序表

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

#define LIST_INIT_SIZE    100
#define LISTLNCREMENT     10
#define OK                1
#define ERROR             0
#define OVERFLOW          -2

typedef int ElemType;

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

int InitList_Sq(SqList &L)
{
L.elem = (ElemType *) malloc(LIST_INIT_SIZE * sizeof(ElemType));
if (!L.elem)
{
exit(OVERFLOW);
}
L.length = 0;
L.listsize = LIST_INIT_SIZE;
return OK;
}

void Create_Sq(SqList &L, int n)
{
int i;
for (i=0; i<n; i++)
{
scanf("%d",&L.elem[i]);
}
L.length = n;
}

void Display_Sq(SqList L)
{
int i;
for (i=0; i<L.length ; i++)
{
printf("%d ",L.elem[i]);
}
printf("\n");
}

int ListInsert_Sq(SqList &L, int i, ElemType e)
{
ElemType *newbase,*p,*q;
if (i<1 || i>L.length+1)
{
return ERROR;
}
if (L.length >= L.listsize)
{
newbase = (ElemType *)realloc(L.elem ,(L.listsize + LISTLNCREMENT) * sizeof(LISTLNCREMENT));
if (!newbase)
{
exit(OVERFLOW);
}
L.elem = newbase;
L.listsize += LISTLNCREMENT;
}
q = &(L.elem [i-1]);
for (p=&(L.elem[L.length-1]);p>=q;--p)
{
*(p+1) = *p;
}
*q = e;
++L.length ;
return OK;
}

int ListDel_Sq(SqList &L, int i, ElemType &e)
{
ElemType *p,*q;
if (i<1 || i>L.length+1)
{
return ERROR;
}

p = &(L.elem [i-1]);
e = *p;
q = L.elem + L.length - 1;
for (++p;p<=q;++p)
{
*(p-1) = *p;
}
--L.length ;
return OK;
}

int compare(ElemType i, ElemType j)
{
return (i==j);
}

int LocateElem_Sq(SqList L, ElemType e, int (*compare)(ElemType, ElemType))
{
ElemType *p;
int i = 1;
p = L.elem;
while (i <= L.length  && !(*compare)(*p++,e))
{
++i;
}
if (i<=L.length)
{
return i;
}
else
{
return 0;
}
}

int main()
{
SqList L;
if (!InitList_Sq(L))
{
printf("链表初始化失败!\n");
}
else
{
int i,n,e;
printf("请输入链表的长度:");
scanf("%d",&n);
printf("请输入 %d 个数据: ",n);
Create_Sq(L,n);
printf("您输入的链表是: ");
Display_Sq(L);
printf("请输入您要插入元素的位置(1~%d):",n);
scanf("%d",&i);
printf("请输入您要插入的元素:");
scanf("%d",&e);
ListInsert_Sq(L,i,e);
printf("插入元素 %d 后的链表是:",e);
Display_Sq(L);
printf("请输入您要删除元素的位置(1~%d):",L.length);
scanf("%d",&i);
ListDel_Sq(L,i,e);
printf("您删除的元素是: %d\n",e);
printf("删除元素后的链表是:");
Display_Sq(L);
printf("请输入您要查找的元素:");
scanf("%d",&e);
i = LocateElem_Sq(L,e,compare);
if (!i)
{
printf("链表中不存在该元素!\n");
}
else
{
printf("%d 位于链表的第 %d 个位置!\n",e,i);
}

}

return 0;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：数据结构 线性表 顺序表 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)