- /*基于结构体数组的链表实现*/
- /* made by winlin 2011.4.11
- *initialize( )初始化存储池
- *insertNode( )插入一个节点
- *deleteNode( )删除一个节点
- *display_member( )显示存储池里面的数据
- *display_info( )显示存储池当前的信息
- *isempty( )存储池是否已满
- */
- #include <iostream>
- #include <cstdlib>
- typedef int elementType;
- const int NULL_VALUE=-1; //不存在的位置
- //节点声明
- typedef struct node
- {
- elementType data; //存放节点的数据
- int next; //存放下一个节点在存储池数组中的序号
- }Node;
- //存储池
- const int NUMNODES=2048;
- Node nodeList[NUMNODES];
- int freelist; //其值为空闲节点链的在存储池中的起始位置
- int first; //其值为第一个节点在存储池中的位置
- int emptyNodes;
- void initialize( )
- {
- int i;
- for( i=0;i<NUMNODES;++i )
- {
- nodeList[ i ].next=i+1;
- }
- nodeList[ NUMNODES-1 ].next=NULL_VALUE;
- freelist=0;
- first=NULL_VALUE;
- emptyNodes=NUMNODES;
- }
- bool isempty( )
- {
- if( emptyNodes==NUMNODES )
- return 1;
- return 0;
- }
- int insertNode(const elementType& nodedata)
- {
- int temp;
- if( emptyNodes<=0 )
- {
- std::cout<<"the NodeList has full/n";
- exit( -1 );
- }
- temp=freelist;
- freelist=nodeList[ freelist ].next; //从空闲链表中剔除开始的那个节点
- if( first==NULL_VALUE )
- {
- first=temp;
- nodeList[ temp].data=nodedata;
- nodeList[ temp].next=NULL_VALUE;
- }
- else
- {
- nodeList[ temp ].data=nodedata;
- nodeList[ temp ].next=first;
- first=temp;
- }
- --emptyNodes;
- return temp;
- }
- void deleteNode(const elementType& nodedata )
- {
- if( first==NULL_VALUE )
- {
- std::cout<<"the NodeList is empty/n";
- exit( -1 );
- }
- int temp_cur=first;
- int temp_pre=first;
- while( temp_cur !=NULL_VALUE)
- {
- if( nodeList[ first ].data==nodedata ) //第一个就是要删除的节点
- {
- int i=first;
- first=nodeList[ i ].next; //处理已使用链
- //处理未使用链
- nodeList[i].next=freelist;
- freelist=i;
- }
- else if( nodeList[ temp_cur].data==nodedata )
- {
- nodeList[temp_pre].next=nodeList[ temp_cur ].next; //处理已使用的链表
- //处理未使用的链表
- nodeList[ temp_cur ].next=freelist;
- freelist=temp_cur;
- }
- temp_pre=temp_cur;
- temp_cur=nodeList[ temp_cur].next;
- }
- ++emptyNodes;
- }
- void display_member( )
- {
- if( emptyNodes==NUMNODES )
- {
- std::cout<<"the NodeList is empty/n";
- exit( -1 );
- }
- int temp=first;
- while(temp!=NULL_VALUE)
- {
- std::cout<<nodeList[ temp ].data<<" ";
- temp=nodeList[ temp ].next;
- }
- std::cout<<"/n";
- }
- void display_info( )
- {
- std::cout<<"NodeList的总容量为:"<<NUMNODES<<"/nNodeList已经使用:"
- <<NUMNODES-emptyNodes<<"/n剩余可用量为:"<<emptyNodes<<"/n";
- }
- int main( )
- {
- initialize( );
- insertNode( 12 );
- insertNode( 13 );
- insertNode( 14 );
- insertNode( 15 );
- insertNode( 16 );
- display_member( );
- display_info( );
- deleteNode(16);
- deleteNode( 12 );
- deleteNode( 13 );
- display_member( );
- display_info( );
- return 0;
- }