1. 程式人生 > >資料結構與演算法——線性表(一)

資料結構與演算法——線性表(一)

#include <stdio.h>
#include <stdlib.h>
#define LIST_INIT_SIZE 200
#define LISTINCREASE 10
#define ERROR 0
#define OK 1
typedef int Elemtype;
typedef int Status;
typedef struct
{
	Elemtype *elem;//儲存的基址
	int length;
	int listsize;//當前分配的儲存容量
}SqList;


/************************************************************************/  
/*建立一個空的線性表 
*/  
/************************************************************************/
Status InitList(SqList &L){
	
	L.elem=(Elemtype *)malloc(LIST_INIT_SIZE*sizeof(Elemtype));
	if(!L.elem) return ERROR;
	L.length=0;
	L.listsize=LIST_INIT_SIZE;
	return OK;
}

/************************************************************************/  
/* 列印list 
*/  
/************************************************************************/  
void PrintList(SqList L){  
    printf("當前值:");   
	for (int i =0; i<L.length;i++) {  
        printf("%d  ", L.elem[i]); // L.elem為首地址  
    }   
    printf("\r\n");   
}  


/************************************************************************/  
/* 獲取第i個位置的元素,返回給e
*/  
/************************************************************************/
Status GetElem(SqList L,int i,Elemtype &e){
	if(L.length==0||i<1||i>L.length)
	{ 
		return ERROR;
	}	
	e=L.elem[i-1];
	return OK;
}


/************************************************************************/  
/* 在第i個位置插入e
*/  
/************************************************************************/
Status InsertList(SqList &L,int i,Elemtype e)
{
	if(i<1||i>L.length+1) return ERROR;
	Elemtype *p,*q;
	q=&(L.elem[i-1]);
	for(p=&(L.elem[L.length-1]);p>=q;--p)
	{
		*(p+1)=*p;
	}
	*q=e;
	++L.length;
	return OK;

}

int main(){
	SqList L;
	InitList(L);
	int i=1;
	int data[6] = {2,3,4,5,6,8};  
        for (i=1; i<6;i++)   
        InsertList(L,i,data[i-1]);   
        PrintList(L);  
	return 0;
}