目录
本笔记用到的宏定义,头文件为define.h
#ifndef __DEFINE_H
#define __DEFINE_H
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
#endif
顺序表(Sequence List)
特点:逻辑上相邻的元素,在物理次序上也是相邻的。
Status函数
Status为函数类型(当return值为函数结果状态时用)
它并不是C语言中原带的关键字,而是自己定义的
如,typedef int Status;
或 typedef char Status;
等
typedef int Status;
Status range(int n)
{
if(n>=30&&n<=100)
return 0;
else
return -1;
}
顺序表的存储结构:
#define SQLMAXSIZE 100
typedef int SqlElemType;
typedef struct __SqList{
SqlElemType *base;
int length;
}Sqlist;
初始化:
Status InitSL(Sqlist *L,int length){
L->base=(SqlElemType *)malloc(sizeof(SqlElemType) * SQLMAXSIZE);
if(!L->base)
return OVERFLOW;
L->length=0;
for(int i=1;i<=length;i++)
{
SQlElemtype e;
scanf("%d",&e);
SQlInsert(L,i,e);
}
return OK;
}
获取元素:
Status GetElem(Sqlist *L,int position,SqlElemType *e)
{
if(position<1||position>L->length)
return ERROR;
*e=L->base[position-1];
return OK;
}
查找元素
int LocateElem(Sqlist *L,SqlElemType e)
{
for(int i=0;i<L->length;i++)
{
if(e==L->base[i])
return i+1;
}
return 0;//0代表查找元素不在顺序表中
}
插入元素:
Status SqlInsert(SQlist *L,int position,SqlElemType e)
{
if(position<1||position>L->length+1)
return ERROR;
if(L->length==SQLMAXSIZE)
return OVERFLOW;
for(int i=L->length-1;i>=position-1;i--){
L->base[i+1]=L->base[i];
}
L->base[position-1]=e;
L->length++;
return OK;
}
删除元素:
Status SqlDelete(Sqlist *L,int position,SqlElemType *e)
{
if(position<1||position>L->length)
return ERROR;
for(int i=position;i<L->length;i++)
{
L->base[i-1]=L->base[i];
}
*e=L->base[position-1];
L->length--;
return OK;
}
销毁、清空、检查为空
销毁:
Status SqlDestroy(Sqlist *L)
{
if(!L->base)
return ERROR;
else{
free(L->base);
return OK;
}
}
清空:
void SqlClear(Sqlist *L) { L->length = 0; }
判断是否为空:
Status SqlIsEmpty(Sqlist *L)
{
if(0==L->length)
return TRUE;
else
return FALSE;
}
顺序表头文件:
#include "define.h"
#include <stdio.h>
#include <stdlib.h>
#ifndef __SEQUENCELIST_H
#define __SEQUENCELIST_H
#define SQLMAXSIZE 100
typedef int SqlElemType;
typedef struct __Sqlist { SqlElemType *base; int length; }
Sqlist; Status InitSL(Sqlist *L, int length);
Status GetElem(Sqlist *L, int position, SqlElemType *e);
int LocateElem(Sqlist *L, SqlElemType e);
Status SqlInsert(Sqlist *L, int position, SqlElemType e);
Status SqlDelete(Sqlist *L, int position, SqlElemType *e);
Status SqlDestroy(Sqlist *L);
void SqlClear(Sqlist *L);
Status SqlIsEmpty(Sqlist *L);
void MergeList(Sqlist *La, Sqlist *Lb);
void Traverse(Sqlist *L);
void MergeList_Seq(Sqlist *La, Sqlist *Lb, Sqlist *Lc);