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

📄 线形表算法.cpp

📁 数据结构(c++版)线性表的全部操作. 创建,查找,删除,添加,合并,顺序定点合并
💻 CPP
字号:
#include <malloc.h>
#include <stdio.h>
#include <iostream.h>
#define TRUE  1
#define FALSE  0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
#define INIT_SIZE 100
#define LISTINCREMENT 10
typedef int ElemType;
typedef struct{
	ElemType *elem;
 	int length;
    int listsize;
   }SqList;

Status InitList_Sq(SqList *L) /*创建一个空的线性表*/
{ 	L->elem=(ElemType *)malloc(INIT_SIZE*sizeof(ElemType));
	if (!L->elem)    exit(ERROR);
	L->length=0;
	L->listsize=INIT_SIZE;  /*申请的空间为初始大小*/
   return OK;
}

Status InsertList_Sq(SqList *L, int i, ElemType e)
/*在线性表的第i个位置前插入元素e*/
{  ElemType * newbase;
  int j;
if (i<1||i>L->length+1) {printf("i值不合法!\n");exit(ERROR);}
	if (L->length>=L->listsize)  /*当前空间已满,增加分配空间*/
	{
		newbase=(ElemType *)realloc(L->elem,(L->listsize+LISTINCREMENT)*sizeof(ElemType));
		if (!newbase) exit(ERROR);
		L->elem=newbase;
		L->listsize= L->listsize+LISTINCREMENT;
	}
    for (j=L->length;j>=i;j--)
		L->elem[j]=L->elem[j-1];
    L->elem[i-1]=e;
	L->length++;   return OK;
}

Status  DeleteList_Sq(SqList *L, int i, ElemType *e)
/* 删除线性表中的第i个元素,并获得所删元素的值*/
{   int j;
	if ((i<1)||(i>L->length)) {printf("i值不合法!\n");exit(ERROR);}
	*e=L->elem[i-1];
	for(j=i;j<=L->length;j++)
		L->elem[j-1]=L->elem[j];
	L->length--;
	return OK;
}

void Print_Sq(SqList *L)
/*遍历顺序线性表*/
{	int i;
	printf("The list:\n");
	for(i=0;i<L->length;i++)
	{
		if ((i+1)%10==0)
		printf("%3d\n",L->elem[i]);
		else
		printf("%3d ",L->elem[i]);
	}
	printf("\nLength=%2d\n",L->length );
}

int equal(ElemType e1,ElemType e2)
/*判两个元素是否相等*/
{
    if (e1==e2) return 1;
	else return 0;
}

int LocateElem_Sq(SqList L,ElemType e)
{
    int i=1;
	while(i<=L.length && !equal(L.elem[i-1],e)) i++;
	if (i<=L.length) return i;
	else return 0;

}

void main()
{ SqList q;
  ElemType e;
  InitList_Sq(&q);
  InsertList_Sq(&q,1,3);
  InsertList_Sq(&q,2,5);
  InsertList_Sq(&q,3,4);
  InsertList_Sq(&q,4,7);
  Print_Sq(&q);
  DeleteList_Sq(&q, 3,&e);
  printf("After Delete the list element:::\n");
  Print_Sq(&q);
  e=LocateElem_Sq(q,5);
  printf("Find the number's location:");
  printf("%5d\n",e);
  
}


   

⌨️ 快捷键说明

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