把事情做漂亮
在链表中,插入和删除的操作需要对第一个结点特殊考虑,使得编程不便,容易出错,使用一个哑结点(dummy node)作为表头就可以解决这个问题。
代码
#ifndef _List_H
struct Node;
typedef struct Node *PtrToNode;
typedef struct PtrToNode List;
typedef struct PtrToNode Position;
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);
Position Header(List L);
Position First(List L);
Position Advance(Position P);
ElementType Retrieve(Position P);
#endif /* _List_H */
/* Place in the implementation file */
struct Node{
ElementType Element;
Position Next;
};
删除结点
/* 测试列表是否为空 */
int IsEmpty(List L){
return L->Next == NULL;
}
/* 测试当前位置是否链表的末尾 */
int IsLast(Position P, List L){
return P->Next = NULL;
}
/* 找到元素X前面一个元素 */
Position FindPrevious(ElementType X, List L){
Position P;
P = L
while(P->Next != NULL && P->Next->Element != X)
P = P->Next;
return P;
}
/* Delete first occurrence of X from a list */
/* Assume use of a header node */
void Delete(ElementType X, List L){
Position P, TmpCell;
P = FindPrevious(X, L);
/* 删除操作结束后,表头保持不变 */
if(!IsLast(P, L)){
TmpCell = P->Next;
P->Next = TmpCell->Next; /* Bypass deleted cell */
free(TmpCell);
}
}
插入结点
/* Insert (after legal position P) */
/* Header implementation assumed */
/* parameter L is unused in this implementation */
void Insert(ElementType X, List L, Position P)
{
Position TmpCell;
TmpCell = malloc(sizeof(struct Node));
if(TmpCell == NULL)
FatalError("Out of Space!!!");
TmpCell->Element = X;
TmpCell->Next = P->Next;
P->Next = TmpCell;
}