⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 顺序表.cpp

📁 c++算法的很经典的一些小练习 看了 觉得还可以 给大家分享一下!
💻 CPP
字号:
#include <stdio.h>
#include <stdlib.h>
#define  LIST_INIT_SIZE     80  
                 // 线性表存储空间的初始分配量
#define  LISTINCREMENT    10 
                // 线性表存储空间的分配增量
#define OK 1
#define OVERFLOW 0
#define ERROR 0
typedef int ElemType;
typedef int Status;
typedef  struct {
ElemType *elem;    // 存储空间基址
int      length;   // 当前长度
int      listsize;  // 当前分配的存储容量  
                         // (以sizeof(ElemType)为单位)
} SqList;  // 俗称 顺序表
Status Creat_Sq( SqList &L );
int LocateElem_Sq(SqList L, ElemType e);
Status ListInsert_Sq(SqList &L,int i, ElemType e );
void main( ){
	SqList L;
	int i,K=1;
	ElemType e,*p;
	if(!Creat_Sq( L )) 
		printf("未生成顺序表");
	else{		
	while(K){
		printf("\n请选择你要进行的操作:\n");
		printf("1 确定位置     2 插入元素\n");
		printf("输入所需操作编码i=");
		scanf("%d",&i);
		switch(i){
		case 1:{
				 printf("输入该元素e=");
				 scanf("%d", &e);
				 i=LocateElem_Sq(L, e);
				 printf("该元素的位置i=%d\n",i);
				 break;
			}
		case 2: {
			printf("输入要插入结点的位置: ");
			scanf("%d",&i);
			printf("输入元素的内容: ");
			scanf("%d",&e);
			ListInsert_Sq(L, i, e );
			printf("该顺序表中的内容:\n");
			for(i=0 ,p=L.elem ;i<L.length ;p++,i++){
				printf("%d    ",*p);
				if(!((i+1)%5)) printf("\n");
			}
			printf("\n该顺序表的长度是: %d\n",L.length );
			break;
				}
		default:printf("输入错误!");
		}
		printf("\n是否要继续进行操作:\n");
		printf("是输入: 1     否输入: 0\n");
		scanf("%d",&i);
		if(i) K=1;
		else	K=0;
	}
	}

	
}
Status  Creat_Sq( SqList &L ) {
  // 构造一个空的线性表 
L.elem = (ElemType*) malloc (LIST_INIT_SIZE*sizeof (ElemType));
if (!L.elem) exit(OVERFLOW);
L.listsize = LIST_INIT_SIZE;
printf("输入要输入的顺序表的长度: ");
scanf("%d", &L.length);
for ( int i=0; i<L.length; i++){
	printf("输入第%d个元素: ",i+1);
	scanf("%d",&L.elem[i]);
}
printf("\n");
return OK;
} // InitList_Sq
int LocateElem_Sq(SqList L, ElemType e) {
   // 在顺序表中查询第一个满足判定条件的数据元素,
  // 若存在,则返回它的位序,否则返回 0
ElemType *p;
int i = 1;           // i 的初值为第 1 元素的位序
p = L.elem;      // p 的初值为第 1 元素的存储位置
while (i <= L.length && *p++!=e)  ++i;
if (i <= L.length)  return i;
else  return 0;
} // LocateElem_Sq
Status ListInsert_Sq(SqList &L,int i, ElemType e ){
	ElemType *q,*p,*newbase;
	if(i<1||i>L.length+1)return ERROR;
	if(L.length>=L.listsize){
		newbase=(ElemType*)realloc(L.elem,(L.listsize+ LISTINCREMENT)*sizeof(ElemType));
		if(!newbase)exit(OVERFLOW);
		L.elem=newbase;
		L.listsize+=LISTINCREMENT;
	}
	q=&(L.elem[i-1]);
	for(p=&(L.elem[L.length-1]);p>=q;--p) *(p+1)=*p;
	*q=e;
	++L.length;
	return OK;
}


 

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -