从零开始的数据结构学习日记(一)——1.1顺序表

一.顺序表

将线性表的元素按照逻辑顺序依次存放在一组地址连续的存储单元里,即逻辑上相邻,物理位置上也相邻。

1.初始化

#define maxsize1024
typedef int datatype;//改类型的话改int成别的就行了
typedef struct
{
	datatype data[maxsize];
	int last;//表示顺序表的长度
}sequenlist;
sequenlist*InitList()
{
	sequenlist*L=(sequenlist*)malloc(sizeof(sequenlist));
	L->last=0;
	return L;
}

2.插入

在线性表第i个位置上插入一个新结点x,并且使表的长度加1,即使表长度变为n+1.

int insert(sequenlist*L,datatype x,int i)
{
	if(L->last==maxsize)
	{
		printf("表已满")return 0}
	else if(i<1||i>L->last)
	{
		printf("非法插入位置")return 0}
	else
	{
		for(int j=L->last;j>=i;i--)
		{
			L->data[j]=L->data[j-1];//结点后移
			L->data[i-1]=x;//把插入元素插入至i的位置上
			L->last++;//表总长度加一
		}
		return 1;
	}
}

复杂度为O(n).

3.删除

和插入很像

int delete(sequenlist*L, int i)
{
	if(i<1||i>L->last)
	{
		printf("非法删除位置")return 0}
	else
	{
		for(int j=i;j<=L->last;j--)
		{
			L->last[j-1]=L->last[j];
			L-last--;
			return 1;
		}
	}	
}

复杂度为O(n).

发布了1 篇原创文章 · 获赞 0 · 访问量 37

猜你喜欢

转载自blog.csdn.net/sakaili/article/details/104032318
今日推荐