一、线性表的抽象数据类型描述
二、线性表的顺序存储实现(数组)
#include <stdio.h>
/*顺序表的数组实现*/
typedef struct LNode *List;
struct LNode{
ElementType Data[MAXSIZE];
int Last;
};
struct LNode L;
List Ptrl;
/*1.初始化*/
List MakeEmpty()
{
List Ptrl;
Ptrl = (List)malloc(sizeof(struct LNode));
Ptrl->Last = -1;
return Ptrl;
}
/*2.查找*/
int Find(ElementType X, List Ptrl)
{
int i = 0;
while(i <= Ptrl->Last && Ptrl->Data[i] != X)
i++;
if(i > Ptrl->Last) return -1;
else return i;
}
/*3.插入*/
void Insert(ElementType X, int i, List Ptrl)
{
int j;
if(Ptrl->Last == MAXSIZE-1){
printf("表满");
return;
}
if(i < 1 || i > Ptrl->Last+2){
printf("位置不合法");
return;
}
for(j = Ptrl->Last; j >= i-1; j--)
Ptrl->Data[j+1] = Ptrl->Data[j];
Ptrl->Data[i-1] = X;
Ptrl->Last++;
return;
}
/*4.删除*/
void Delete(int i, List Ptrl)
{
int j;
if(i < 1 || i > Ptrl->Last+1){
printf("不存在第%d个元素",i);
return;
}
for(j = i; j <= Ptrl->Last; j++)
Ptrl->Data[j-1] = Ptrl->Data[j];
Ptrl->Last--;
return;
}
三、线性表的链式存储实现
#inlcude <stdio.h>
/*顺序表的链式存储实现*/
typedef struct LNode *List;
struct LNode{
ElementType Data;
List Next;
};
struct LNode L;
List Ptrl;
/*1.求表长*/
int Length(List Ptrl)
{
List p = Ptrl;
int j = 0;
while(p) {
j++;
p = p->Next;
}
return j;
}
/*2.查找*/
List FindKth(int K, List Ptrl)
{
List p = Ptrl;
int i = 1;
while(p != NULL && i < K){
p = p->Next;
i++;
}
if(i == K)return p;
else return NULL;
}
/*3.插入*/
List Insert(ElementType X, int i, List Ptrl)
{
List p,s;
if(i == 1){
s = (List)malloc(sizeof(struct LNode));
s->Data = X;
s->Next = Ptrl;
return s;
}
p = FindKth(i-1, Ptrl);
if (p == NULL){
printf("参数i错误");
return NULL;
}else{
s = (List)malloc(sizeof(struct LNode));
s->Data = X;
s->Next = p->Next;
p->Next = s;
return Ptrl;
}
}
/*4.删除*/
List Delete(int i, List Ptrl)
{
List p,s;
if(i == 1){
s = Ptrl;
if(Ptrl != NULL) Ptrl = Ptrl->Next;
else return NULL;
free(s);
return Ptrl;
}
p = FindKth(i-1,Ptrl);
if(p == NULL){
printf("第%d个节点不存在",i-1);
return NULL;
}else if (p->Next == NULL){
printf("第%d个节点不存在",i);
return NULL;
}else{
s = p->Next;
p->Next = s->Next;
free(s);
return Ptrl;
}
}