简单介绍下链表:链表就是由任意N个节点组成的不连续的空间。节点由所存储数据和指向下一个节点的指针构成。
struct list{
type data;
struct list * next;
};
双向循环链表:每个节点由数据,指向上一个节点的指针,指向下一个节点的指针构成。并且尾节点的NEXT指针指向头节点。头节点的PREV指针指向尾节点。
struct List{
T data;
List * prev;
List * next;
};
链表构建容易错误的地方在于插入和删除。
插入:我们把N节点插入P节点之后。需要1.用N的NEXT指针指向P的下一个节点L。2用L的PREV指针指向N。3.用N的PREV指针指向P。
删除:删除时我们一般
1.建立一个指针TMP指向所要删除的P节点的下一个节点。
2.将P的前一个节点的NEXT指向P的下一个节点。将P孤立出来。
3.释放P的空间并把TMP赋予P,以便删除下面的节点。
//双向循环链表
#include<new>
#include<iostream>
template <typename T> struct ListNode{
T data;
ListNode<T> * prev;
ListNode<T> * next;
};
template <typename T>
class Class_List{
private:
typedef ListNode<T> * PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
List L;//头节点
public:
List MakeEmpty ( )//建立一个空树
{
L = new ListNode<T>;
L->data = 0 ;
L->prev = L->next = L;
return L;
}
bool IsEmpty ( )
{
return L->next == L;
}
bool IsLast ( Position P )
{
return P->next == L;
}
Position Find ( T X )
{
Position P;
P = L;
while( P->next != L && P->data != X)
P = P->next;
return P;
}
void Delete ( T X )//删除一个值所在的节点
{
Position P = Find( X );
//P->prev->next = P->next;
//P->prev->next->prev = P->prev
//delete P;
Position Pro = P->prev;
Position Nex = P->next;
Pro->next = Nex;
Nex->prev = Pro;
delete P;
}
void Delete (Position P)
{
Position Pro = P->prev;
Position Nex = P->next;
Pro->next = Nex;
Nex->prev = Pro;
delete P;
}
Position FindPrevious ( T X )
{
Position P = Find( X );
return P->prev;
}
void Insert ( T X , Position P )//插入P节点之后
{
Position N = new ListNode<T>;
N->data = X;
N->prev = P;
N->next = P->next;
P->next = N;
N->next->prev = N;
}
void Insert( T X )
{
Position P = L->prev;
Position N = new ListNode<T>;
N->data = X;
N->prev = P;
N->next = P->next;
P->next = N;
N->next->prev = N;
// std::cout<<N->data<<std::endl;
}
void DeleteList ( )
{
Position p;
for( p = L->next ; p != L ; )
{
Position tmp = p->next;
Delete( p );
p = tmp;
}
delete L;
std::cout<<"delete"<<std::endl;
}
Position Header ( )
{
return L;
}
Position Fist ( )
{
return L;
}
void show()
{
std::cout<<"show"<<std::endl;
if( L == NULL )
{
std::cout<<"the list is empty"<<std::endl;
return ;
}
Position p;
for( p = L ; p->next != L ; p=p->next)
{
std::cout<<p->data<<" ";
}
std::cout<<L->prev->data<<std::endl;
std::cout<<std::endl;
}
Class_List()
{
L = MakeEmpty ( );
}
Class_List( T value[] , int length )
{
L = MakeEmpty();
Position p = L;
int i = 0;
while ( i < length )
{
Insert( value[i] , p);
i++;
p = p->next;
}
}
~Class_List ()
{
DeleteList( );
}
};