表ADT可以通过数组、单链表、双链表、循环链表等结构实现。
数组表示方法就是所谓的静态链表,用于不支持指针的场合。
单链表有后继元,每个元素包含一个指向后一个元素的指针。
双链表有前驱元和后继元,每个元素包含一个指向前一个元素的指针(除了头结点)以及一个指向后一个元素的指针(除了尾节点)。
循环链表有前驱元和后继元,它和双链表类似,不同之处在于它的尾结点的后继元指向头结点,头结点的前驱元指向尾结点。
一、链表实现的表
这里使用多项式链表来表示,它和单链表的不同之处就是多了一个元素,其余部分相同。
下面部分代码实现多项式链表相加、相乘(按幂排序)操作。
#include <iostream>
#include <cstdlib>
using namespace std;
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode Polynormial;
typedef PtrToNode List;
typedef PtrToNode Position;
typedef int ElementType;
//多项式链表结构体
struct Node
{
ElementType Coefficient;//系数
ElementType Exponent;//幂指数
PtrToNode Next;
};
int IsEmpty(List L)
{
return L->Next == NULL;
}
int IsLast(Position P, List L)
{
return P->Next == NULL;
}
Position FindCoef(ElementType X, List L)
{
Position P;
P = L->Next;
while (P != NULL && P->Coefficient != X)
P = P->Next;
return P;
}
Position FindExp(ElementType X, List L)
{
Position P;
P = L->Next;
while (P != NULL && P->Exponent != X)
P = P->Next;
return P;
}
Position FindPreviousCoef(ElementType X, List L)
{
Position P;
P = L;
while (P->Next != NULL && P->Next->Coefficient != X)
P = P->Next;
return P;
}
Position FindPreviousExp(ElementType X, List L)
{
Position P;
P = L;
while (P->Next != NULL && P->Next->Exponent != X)
P = P->Next;
return P;
}
void DeleteCoef(ElementType X, List &L)
{
Position P, TmpCell;
P = FindPreviousCoef(X, L);
if (!IsLast(P, L))
{
TmpCell = P->Next;
P->Next = TmpCell->Next;
free(TmpCell);
}
}
void DeleteExp(ElementType X, List &L)
{
Position P, TmpCell;
P = FindPreviousExp(X, L);
if (!IsLast(P, L))
{
TmpCell = P-