数据结构与算法分析——c语言描述
第3章 第二节 表
1.带头结点(原书) 稍微改造一下
#include <stdio.h>
#include <stdlib.h>
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
typedef int ElementType;
struct Node
{
ElementType Element;
Position Next;
};
void FatalError(const char *s)
{
printf("%s", s);
exit(-1);
}
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;
P = L->Next;
while(P != NULL && P->Element != X)
P = P->Next;
return P;
}
Position FindPrevious(ElementType X, List L)
{
Position P;
P = L;
while(P->Next != NULL && P->Next->Element != X)
P = P->Next;
return P;
}
void Delete(ElementType X, List L)
{
Position P, TmpCell;
P = FindPrevious(X, L);
if(! IsLast(P, L))
{
TmpCell = P->Next;
P->Next = TmpCell->Next;
free(TmpCell);
}
}
void Insert(ElementType X, List L, Position P)
{
Position TmpCell;
TmpCell = (Position)malloc(sizeof(struct Node));
if(!TmpCell)
FatalError("Out of space!");
TmpCell->Element = X;
TmpCell->Next = P->Next;
P->Next = TmpCell;
}
void Destroy(List L)
{
Position P;
while(L)
{
P = L;
L = L->Next;
free(P);
}
}
void Travel(List L)
{
while(L->Next)
{
printf("%d ", L->Next->Element);
L = L->Next;
}
printf("\n");
}
int main(void)
{
List L = (List)malloc(sizeof(struct Node));
if(!L)
FatalError("Out of space!");
int i;
Position P = L;
for(i = 1; i <= 5; i++)
{
/* Insert(i, L, P); //尾插
P = P->Next; */
Insert(i, L, L);
}
P = L;
Travel(L);
int n;
printf("Input the number you want to delete:");
scanf("%d", &n);
Delete(n , L);
Travel(L);
Destroy(L);
return 0;
}
2.不带头结点
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
struct Node
{
ElemType data;
struct Node *next;
};
typedef struct Node* Pnode;
void Insert(Pnode *p, int data, int i)
{
int j = 1;
Pnode pp = *p;
if(i == 1)
{
*p = (Pnode)malloc(sizeof(struct Node));
(*p)->data = data;
(*p)->next = pp;
return ;
}
while(pp && j < i -1)
{
pp = pp->next;
j++;
}
if(!pp)
{
printf("Out of bordor!\n");
exit(-1);
}
Pnode s = (Pnode)malloc(sizeof(struct Node));
s->data = data;
s->next = pp->next;
pp->next = s;
}
void Delete(Pnode *p, int i)
{
int j = 1;
Pnode temp = *p, t;
if(i == 1)
{
*p = temp->next;
free(temp);
return ;
}
while(temp && j < i - 1)
{
temp = temp->next;
j++;
}
if(!temp)
{
printf("Outer of bordor!\n");
exit(-1);
}
t = temp->next;
temp->next = t->next;
free(t);
}
void Travel(Pnode p)
{
while(p)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void Destroy(Pnode p)
{
Pnode temp;
while(p)
{
temp = p;
p = p->next;
free(temp);
}
}
int main()
{
Pnode p = NULL;
int i = 1;
for(; i <= 5; i++)
{
Insert(&p, i, i);
}
Travel(p);
printf("Input the location you want to delete:");
int n;
scanf("%d", &n);
Delete(&p, n);
Travel(p);
Destroy(p);
return 0;
}
3.个人总结
插入删除是表操作里的重点内容,而链表的插入和删除要把握好“前一个”概念,要操作当前节点,必须要找到它的前一个节点的指针。
带头节点的链表在对第一个节点操作时明显优于不带头结点的的链表!