链表是一种最常用的数据结构,其他的数据结构也可以由链表实现,链表由一系列不必在内存中相连的结构组成,每一个结构均含有表元素和指向该元素后继元的结构的指针,称为Next指针,为了方便理解,我们把这样的结构称为节点,最后一个节点的Next指针指向NULL,有的情况下,还为链表添加一个头节点,可以防止在删除链表的第一个元素时,丢失链表,如下图所示:
对链表的操作通常是创建一个链表,从链表中删除元素,向链表中插入元素等,如果理解了链表的概念,这些操作很容易实现。
链表的实现与操作代码如下:
#include <iostream> //包含头文件iostream
using namespace std; //使用命名空间std
typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
struct Node
{
int Element;
Position Next;
};
函数声明///
List MakeEmpty (); //创建一个空链表
int IsEmptu (List L); //测试一个链表是否为空
int IsLast (Position P, List L); //测试当前位置是否是链表的末尾
Position Find (int x, List L); //寻找链表中的元素x
Position FindPrevious (int x, List L); //寻找元素x的前驱元
void Delete (int x, List L); //删除元素x
void Insert (int x, List L, Position P); //插入元素x
void DeleteList (List L); //删除一个表
函数定义///
List MakeEmpty ()
{
List Header;
Header = static_cast<List>(malloc(sizeof (struct Node))); //创建一个表头
Header->Element = 0;
Header->Next = NULL;
return Header;
}
int IsEmptu (List L)
{
return L->Next == NULL;
}
int IsLast (Position P, List L)
{
return P->Next == NULL;
}
Position Find (int x, List L)
{
Position P;
P = L->Next ;
while (P != NULL && P->Element != x)
P = P->Next ;
return P;
}
Position FindPrevious (int x, List L)
{
Position P;
P = L;
while (P->Next != NULL && P->Next->Element != x)
{
P = P->Next ;
}
return P;
}
void Delete (int 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 (int x, List L, Position P)
{
Position TmpCell;
TmpCell = static_cast<Position>(malloc(sizeof (struct Node))); //创建一个新的结点
if(TmpCell == NULL)
cout << "out of space!!" << endl;
TmpCell->Element = x;
TmpCell->Next = P->Next ;
P->Next = TmpCell;
}
void DeleteList (List L)
{
Position P, Tmp;
P = L->Next ;
L->Next = NULL;
while (P != NULL)
{
Tmp = P->Next ;
free(P);
P = Tmp;
}
}
int main ()
{
/测试链表/
List L = MakeEmpty ();
Insert (4,L,L);
cout << L->Next->Element << endl;
return 0;
}
还有其他很多操作,比如打印链表等,都可以按照上面的思想实现,重要的是理解链表的基本思想。
夜深了,天什么时候才会亮。