首先我们得明白什么是线性表。
根据定义:零个或多个数据元素的有序序列
从这个定义看出:(1)顺序性:元素与元素之间是有顺序的;(2)空的线性表也是允许存在;(3)线性表是有限的,否则怎么办?(大家懂的)
因此,可以这么说,线性表在逻辑结构和物理结构上都是有顺序的。
数据元素是结构体,一般来说。。关于结构体的讨论,我会放在c++primer里进行讨论。
基本的线性表的操作有哪些?
节点的定义:
typedef struct Node{
ElemType elem; //数据元素
int n; //次数
int leagth; //表长
struct Node *next; //节点指针
}ListNode; //其他的数据项根据具体条件添加
线性表的初始化,删除,插入,取值操作
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define OK 1
#define OVERFLOW -2
#define ERROR -1
typedef int ElemType;
typedef int Status;
typedef struct
{
ElemType *elem; //存储空间基址
int length;
int listsize;
}SqList;
Status InitList_Sq(SqList *L)
{
L->elem=(ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType)); //存储分配地址
if(!L->elem)
exit(OVERFLOW);
L->length=0; //空表长度
L->listsize=LISTINCREMENT; //初始容量
return OK;
}
Status ListInsert_Sq(SqList *L,int i,ElemType e)
{
ElemType *newbase;
ElemType *q;
ElemType *p;
if(i<1||i>(L->length+1)) //判断i的位置是否合法
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]); //q为插入位置
for(p=&(L->elem[L->length-1]);p>=q;--p)
{
*(p+1)=*p; //插入位置及之后的元素右移
}
*q=e; //插入e
++L->length; //表长增1
return OK;
}
Status ListDelete_Sq(SqList *L,int i,ElemType e) //删除第i个元素
{
ElemType *p;
ElemType *q;
if(i<1||i>(L->length+1))
return ERROR;
p=&(L->elem[i-1]); //p为被删除的位置
e=*p;
q=L->length-1+L->elem; //表尾的位置
for(p+1;p<=q;p--)
{
*(p-1)=*p;
}
--L->length;
return OK;
}
Status GetElem_Sq(SqList *L,int i,ElemType e)
{
ElemType *p;
ElemType *q;
if(i<1||i>(L->length+1))
return ERROR;
p=&(L->elem[i-1]);
e=*p;
return e;
}
int main()
{
Status InitList_Sq ( SqList *L );
SqList L;
int i,j;
int n ;
printf("请输入数的个数:\n");
scanf("%d",&n);
InitList_Sq ( &L );
//对表进行赋值
for(i=1;i<=n;i++){
scanf("%d",&L.elem[i-1]);
++L.length;
}
//输出表中的值
for(j=1;j<=n;j++)
printf("%d ",L.elem[j-1]);
system("pause");
return 0;
}