c语言实现顺序性链表

注意事项:

  1. 改变元素个数时更新lenth
  2. 进行增添元素时检查表是否满
  3. 插入、删除时检查位置是否合法
  4. 能用取地址符号就尽量用,代码简洁
  5. 库函数realloc的用法

原理分析:
SqList结构体变量只需要提供一个指针的头部,剩下的操作都由函数完成

#include
#include
#include
#define ElemType int
#define List_Init_Size 100 
#define List_Increament 10
#define OK 1 

typedef struct {
	ElemType *elem;//链表的头 
	int lenth;
	int listsize;
}SqList;

int InitList_Sq(SqList &L)  //初始化创建链表
{
	L.elem = (ElemType *)malloc(List_Init_Size*(sizeof(ElemType)));
	if(!L.elem)exit(-1);
	L.lenth = 0;
	L.listsize = 0;
	return OK;
}

ElemType GetElem_Sq(SqList L,int i){   //得到元素
	return L.elem[i-1];
}

int ListInsert_Sq(SqList &L,int i,ElemType e){   //插入元素
	if((i<1)||(i>L.lenth+1)) exit(-1);    //判断位置是否合法
	if(L.lenth>=L.listsize){                //判断表是否满了
		ElemType *newbase = (ElemType *)realloc(L.elem,(L.listsize+List_Increament)*sizeof(ElemType));
		if(!newbase)exit(-1);
		L.elem = newbase;
		L.listsize += List_Increament;
	} 
  //能用取地址符号就尽量用取地址符号,但是只能对连续的空间用 
	ElemType *p = NULL;
	for(p = &L.elem[L.lenth-1];p>=&L.elem[i-1];p--) *(p+1) = *p;
	L.elem[i-1] = e;
	L.lenth++;
	return OK; 
}

int ListAppend_Sq(SqList &L,ElemType e){    //尾插
	if(L.lenth>=L.listsize){            //判断是否满了
		ElemType *newbase = (ElemType *)realloc(L.elem,(L.listsize+List_Increament)*sizeof(ElemType));
		if(!newbase)exit(-1);
		L.elem = newbase;
		L.listsize +=List_Increament;
	}
	L.elem[L.lenth] = e;
	L.lenth++;
	return OK;
}

int ListDelete_Sq(SqList &L,int i,ElemType e){    //删除元素
	if((i<1)||(i>L.lenth))exit(-1);             //判断位置是否合法
	e = L.elem[i-1];
	ElemType *p = NULL;
	for(p = &L.elem[i];p <= &L.elem[L.lenth-1];p++) *(p-1) = *p;
	L.lenth--;
	return OK;
}

void ListPrint_Sq(SqList L)
{
	for(int i = 0;i<L.lenth;i++)
	{
		printf("第%d个元素是%d\n",i+1,L.elem[i]);
	}
}


main()
{
	SqList L;
	ElemType e;
	InitList_Sq(L);
	ListInsert_Sq(L,1,23);
	ListAppend_Sq(L,16);
	ListInsert_Sq(L,2,15);
	ListDelete_Sq(L,2,e);
	ListPrint_Sq(L);

}

输出:

第1个元素是23
第2个元素是16

你可能感兴趣的:(c)