1、顺序结构线性表定义
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
//定义
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 200
typedef int status;
typedef struct
{
int data[MAXSIZE];
int length;
}sqlist,*psqlist;
//初始化
status Inintsqlist(psqlist list)
{
list->length=0;
return OK;
}
//判断是否为空
status checksqlist(psqlist list)
{
if (list->length == 0)
{
return FALSE;
}else
{
return TRUE;
}
}
//置空
status Emptysqlist(psqlist list)
{
list->length=0;
return OK;
}
//获取长度
int GetLength(psqlist list)
{
return list->length;
}
//插入元素
status InsertElemdata(psqlist list,int pos,int& e)
{
if (list->length >= MAXSIZE)
return ERROR;
if (pos<=0 || pos > list->length+1)
return ERROR;
if (pos < list->length)
{
for(int i=list->length-1;i>=pos-1;i--)
{
list->data[i+1]=list->data[i];
}
}
list->data[pos-1]=e;
list->length++;
return OK;
}
//删除元素
status delElemData(psqlist list,int pos,int& e)
{
if (list->length ==0 || pos>list->length || pos<1)
return ERROR;
e=list->data[pos-1];
if (pos <list->length)
{
for (int i=pos;i<list->length;i++)
{
list->data[i-1]=list->data[i];
}
}
list->length--;
return OK;
}
//查找元素 根据位置得到数据内容
int GetElem(psqlist list,int pos,int& e)
{
if (pos<=0 || pos > list->length+1)
return ERROR;
e= list->data[pos-1];
return e;
}
//根据元素查找 数据位置
int LocateElem(psqlist list,int& e)
{
for (int i=0;i<list->length-1;i++)
{
if (list->data[i] == e)
return i+1;
}
return 0;
}
//合并两个顺序表
void UnionL(psqlist list1,psqlist list2)
{
int len1=list1->length;
for (int i=1;i<=list2->length;i++)
{
if (!LocateElem(list1,list2->data[i-1]))
{
InsertElemdata(list1,++len1,list2->data[i-1]);
}
}
}
//遍历数据
void Trvallist(psqlist list)
{
for (int i=0;i<list->length;i++)
{
printf("%d",list->data[i]);
}
printf("\n");
}
2、链式结构线性表定义