嵌入式菜鸟算法②---顺序表操作

主要内容:顺序表插入、删除

特点:存储结构和逻辑结构顺序一样

最大优点:可以方便的随机存取表中任一个结点

缺点:

a、插入或删除操作,除表尾的位置外,其它位置必须移动大量的结点,平均要移动约一半的结点,平均时间复杂度为O(n),效率较低

b、顺序表所占空间必须是连续的,结点数并不固定,只能预先分配空间(静态分配)。难以确定合适的存储空间

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

#define MAXSIZE 1024
typedef int datatype;

typedef struct
{
	datatype data[MAXSIZE];
	int last;   // subscript of linear list's last node,i.e. length is n  = last + 1 
}sequenlist;

/* linear list insert operate */
int Insert(sequenlist* L, datatype x, int i)
{
	int j;
	if (L->last >= MAXSIZE - 1)
	{
		printf("space overflow!\n");
		return 0;
	}
	else if (i < 1 || (i > L->last + 2))
	{
		printf("insert in a invalide position!\n");
		return 0;
	}
	else
	{
		for (j = L->last; j >= i-1; j--)
		{
			L->data[j+1] = L->data[j];  // give space for insert new data 
		}
		L->data[i-1] = x;
		L->last = L->last+1;
	}
	return 1;
}

/* linear list delete operate */
int Delete(sequenlist* L, int i)
{
	int j;
	if (i < 1 || (i > L->last + 1))
	{
		printf("delete position is invalide!\n");
		return 0;
	}
	else
	{
		for (j = i; j <= L->last; j++)
		{
			L->data[j-1] = L->data[j];
		}
		L->last = L->last-1;
	}
	return 1;
}
int main()
{
	sequenlist *L;
	int i, ch, n;
	
	while(1)  // shouw the menu
	{
		printf("\n*****Please select:");
		printf("\n(1) input sequenlist");
		printf("\n(2) insert sequenlist");
		printf("\n(3) delete sequenlist");
		printf("\n*****End*************");
		
		ch = getch();  // get keyboard input
		
		switch(ch)
		{
			case '1':
				printf("\nPlease input your sequenlist's number n = ");
				scanf("%d", &n);
				
				L = (sequenlist*)malloc(sizeof(sequenlist));
				
				for (i = 0; i < n; i++)
				{
					printf("\n Please input %dth interger:", i+1);
					scanf("%d", &L->data[i]);
				}
				L->last = n-1;
				printf("your input sequenlist is:\n");
				for (i = 0; i<=L->last; i++)
				{
					printf("%d\n", L->data[i]);
				}
				break;
			case '2':
				printf("\n Please input the value to insert:");
				scanf("%d", &n);
				printf("\nPlease input the position to insert");
				scanf("%d", &i);
				printf("\n");
				
				if (Insert(L, n, i))
				{
					printf("the insert result is:\n");
					for (i = 0; i <= L->last; i++)
					{
						printf("%d", L->data[i]) ;
						printf("\n");
					}
				}
				break;
				
		    case '3':
			  	printf("\n Please input the delete data's position:");
			  	scanf("%d", &i);
			  	printf("\n");
			  	if (Delete(L, i))
			  	{
	  				printf("the delete result is:\n");
	  				
	  				for (i = 0;  i<=L->last; i++)
	  				{
				  		printf("%d\n", L->data[i]);
				  		
				  	}
	  			}
	  			break;
	  			
 			case '4':
 			return;
 			
 			default:
			 return; 
		}
	}
	return 0;
}

输出结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值