- 声明指向一个结构的指针并不创建该结构,而只是给出足够的空间容纳结构可能会使用的地址。
- malloc(sizeof(PtrToNode))是合法的,但是它并不给结构体分配足够的空间。它只给指针分配一个空间。
- Find 、 FindPrevious 、Delete 函数最坏情况运行时间是$O(N)$,其余的都为$O(1)$,因为不管表多大都只执行固定数目的指令。
#include <cstdio>
#include <cstdlib>
#include <malloc.h>
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
typedef int ElementType;
List MakeEmpty(List L);
int IsEmpty(List L);
int IsLast(Position P,List L);
Position Find(ElementType X,List L);
void Delete(ElementType X,List L); // 删除第一次出现的X元素
Position FindPrevious(ElementType X,List L);
void Insert(ElementType X,List L,Position P);
void DeleteList(List L);
Position Header(List L);
Position First(List L);
Position Advance(Position P);
ElementType Retrieve(Position P);
struct Node
{
ElementType Element;
Position Next;
};
int IsEmpty(List L)
{
return L->Next == NULL;
}
int IsLast(Position P,List L)
{
return P->Next == NULL;
}
Position Find(ElementType X,List L)
{
Position P = NULL;
P = L->Next;
while(P!=NULL && P->Element != X)
{
P=P->Next;
}
return P;
}
Position FindPrevious(ElementType X,List L)
{
Position P = L;
while(P->Next!=NULL && P->Next->Element!=X)
{
P = P->Next;
}
return P;
}
void Delete(ElementType X,List L)
{
Position P = FindPrevious(X,L);
if(!(IsLast(P,L)))
{
Position TmpCell = P->Next;
P->Next = TmpCell -> Next;
free(TmpCell);
}
}
void Insert(ElementType Element,List L,Position P)
{
Position TmpCell = Position(malloc(sizeof(struct Node)));
if(!TmpCell)
{
printf("Out of Space\n");
}
TmpCell->Element = Element;
TmpCell->Next = P->Next;
P->Next = TmpCell;
}
void DeleteList(List L)
{
Position P = L->Next;
L->Next = NULL;
Position TmpCell;
while(P!=NULL)
{
TmpCell = P;
P = P->Next;
free(TmpCell);
}
}
List Create()
{
List L = List(malloc(sizeof(struct Node)));
L->Next = NULL;
Position PrePosition = L;
for(int i = 1; i<=5;++i) { Insert(i,L,PrePosition); PrePosition = PrePosition -> Next;
}
return L;
}
void Print(List L)
{
Position P = L->Next;
while(P!=NULL)
{
printf("%d",P->Element);
P=P->Next;
if(P!=NULL)
{
printf(" ");
}
}
printf("\n");
}
Position Header(List L)
{
return L;
}
Position First(List L)
{
return L->Next;
}
Position Advance(Position P)
{
return P->Next;
}
ElementType Retrist(Position P)
{
return P->Element;
}
int main()
{
List L = Create(); // Create()函数是作测试用
Print(L);
return 0;
}