定义结点结构
typedef struct LNode *PtrToLNode;
struct LNode
{
ElementType Data;
PtrToLNode Next;
};
typedef PtrToLNode Position; /*结点的地址?*/
typedef PtrToLNode List;
List L;
1.求表长
int Length(List L)
{
Position p;
int cnt=0;
p=L; /*p指向表的第一个结点*/
while(p)
{
p=p->Next;
cnt++;
}
return cnt;
}
2.查找
(1)按序号查找FindKth
#define ERROR -1 /*一般定义为表中元素不可能取到的值*/
ElementType FindKth(List L, int K)
{
Position P;
int cnt=1;
p=L;
while(p&&cnt<K)
{
p=p->Next;
cnt++;
}
if((cnt==K)&&p) return p->Data;
else return ERROR;
}
(2)按值查找,即定位Find
#define ERROR NULL /*用空地址表示错误*/
Position Find(List L, ElementType X)
{
Position P;
p=L;
while(p&&p->Data!=X)
{
p=p->Next;
}
if(p) return p;
else return ERRPR;
}
3.插入
(1)不带头结点
#define ERROR NULL /*用空地址表示错误*/
List Insert(List L,ElementType X,int i)
{
Position tmp,pre;
tmp=(Position)malloc(sizeof(struct LNode));
tmp->Data=X; /*赋值可以在循环之前?*/
/*如果新结点插入在表头*/
if(i==1)
{
//tmp->Data=NULL;
tmp->Next=L;
return tmp;
}
else
{
int cnt=1; /*查找位序为i=1的结点*/
pre=L;
while(pre&&cnt<i-1)
{
pre=pre->Next;
cnt++;
}
if(pre==NULL||cnt!=i-1) /*所找结点不在L中*/ /*为什么是或?*/
{
printf("插入位置参数错误\n");
free(tmp);
return ERROR;
}
else
{
/*找到了待插结点的前一个结点pre*/
/*插入新结点,并返回表头L*/
tmp->Next=pre->Next;
pre->Next=tmp;
return L;
}
}
}
(2)带头结点
bool Insert(List L,ElementType X,int i)
{
/*这里默认L有头结点*/
Position tmp,pre;
int cnt=0;
pre=L;
while(pre&&cnt<i-1)
{
pre=pre->Next;
cnt++;
}
if(pre==NULL||cnt!=i-1)
{
printf("插入位置参数错误\n");
return false;
}
else
{
tmp=(Position)malloc(sizeof(struct LNode));
tmp->Data=X;
tmp->Next=pre->Next;
pre->Next=tmp;
return true;
}
}
4.删除
bool Delete(List L,int i)
{
/*这里默认L有头结点*/
Position tmp,pre;
int cnt=0;
pre=L;
while(pre&&cnt<i-1)
{
pre=pre->Next;
cnt++;
}
if(pre==NULL||cnt!=i-1||pre->Next==NULL)
{
/*所找结点或位序为i的结点不在L中*/
/*pre==NULL||cnt!=i-1表示位序为i-1的结点不在L中*/
/*pre->Next==NULL表示位序为i的结点不在L中*/
printf("插入位置参数错误\n");
return false;
}
else
{
tmp=pre->Next;
pre->Next=tmp->Next;
free(tmp);
return true;
}
}