顺序表的 C 语言实现

版权声明:本文为博主原创文章,若转载请注明出处且不得删改。(如有错误请提出指正,部分文章会参考其他文章,已经表明参考出处,如有侵权请联系删除) https://blog.csdn.net/qq_34902437/article/details/82959139
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define OVERFLOW 0
#define ERROR -1
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef int ElemType;
typedef struct 
{
//	定义数组存储数据元素的最大值 
	char *elem;
//	定义线性表当前长度 
	int length;
//	线性表的长度
	int listsize; 
}SqList;

//	线性表的初始化
int InitList(SqList &L)
{
	L.elem = (char *)malloc(LIST_INIT_SIZE*sizeof(char));
	if(!L.elem)
		exit(OVERFLOW);
		
	L.length = 0;
	L.listsize = LIST_INIT_SIZE;
	return OK;
 } 
 
// 插入
int ListInsert_Sq(SqList &L,int i,char e)
{
//	i 是要插入的位置 
//	如果要插入的位置不在顺序表的范围内就报错 
	if(i<1 || i>L.length)
	{
		return ERROR;
	}
	
	char *newbase;
	char *p , *q;
//	如果当前长度大于了最大长度就重新分配新的空间 
	if(L.length >= L.listsize)
	{
		newbase = (char*)realloc(L.elem,(L.listsize+LISTINCREMENT)*sizeof(char));
		if(!newbase)
			exit(OVERFLOW);
		L.elem = newbase;
		L.listsize += LISTINCREMENT;
	}
	
//	插入操作

//	q 为第 i 个元素的位置 ,即要插入的元素的位置 
q = &(L.elem[i-1]); 

//	从后往前遍历,把 i 后的每一个元素都后移一位 
for(p=&(L.elem[L.length - 1]);p>=q;p--)
{
	*(p+1) = *p;
}

//	把要插入的元素放到 i 这个位置 
*q = e;

//顺序表当前长度增加一个 
L.length++;

return OK;
 } 
 
// 删除
int ListDelet_Sq(SqList &L,int i)
{
	int k; 
	
	if(i<1 || i>L.length)
	{
		return ERROR;
	}

	if(i<L.length)
	{
		for(k=i;k<L.length;k++)
		{
			L.elem[k-1] = L.elem[k];
		}
	}
	

	
	L.length--;
	return OK;
 } 
 
// 查找
// x 为查找的值 
int LocateElem_Sq(SqList L,char x)
{
	int i = 1;
	char *p;
 	p = L.elem;
 	while(i<L.length)
 	{
 		if(*p == x)
 			break;
 		else
 			p++;
 			i++;
	 }
	 
//	 返回这个位置 
	printf("%d 的位置是 %d\n",x,i);
 } 
 
// 显示当前顺序表的数值
void show(SqList L)
{
	int i;
	printf("当前顺序表的数值情况:\n");
	for(i=0;i<L.length;i++)
	{
		printf("%d ",L.elem[i]);
	}
	printf("\n");
 } 
 
 main()
 {
 	int y;
 	SqList L;
 	y = InitList(L);
 	if(y == 1)
 		printf("success init\n");
 		
// 	先给顺序表赋值
	for(int i=0;i<10;i++)
	{
		L.elem[i] = i;
		L.length ++ ;		
	}
	
	show(L);
 
// 	查找一个数字 8 ,并返回它的位置
	 LocateElem_Sq(L,8); 
	 
//	 插入一个数字 10 到第八位置
	ListInsert_Sq(L,8,10);
	show(L); 
	
//	删除一个数字 10  
	 ListDelet_Sq(L,8);
	 show(L); 
	
//	这个是地址 
//	 printf("%d\n",L);


 }
 
 

猜你喜欢

转载自blog.csdn.net/qq_34902437/article/details/82959139