对块状链表不熟悉的请移步
1.链表节点(block):
block加入模板
template<class ElemType>
构造函数
block<ElemType>(block<ElemType>* to,block<ElemType>* p):next(to),pre(p)
①:属性
ElemType data[MAXN];
int len ; /*本block有效数据的长度*/
bool rev ;
block<ElemType> *next , *pre ;
并添加基本操作:分割,合并,删除下一个块
②:分割
在本块的指定位置处分割
void split(int pos) /*分裂,在pos处,分裂成->[0,pos)->[pos,len)->*/
{
if( pos >= len || pos <= 0 ) return ; /*非法位置*/
if( this->rev )/*在某例中可能出现的反转情况*/
{
reverse(this->data,this->data+this->len);
this->rev = 0 ;
}
block<ElemType>* newblock = new block<ElemType>(this->next,this);
if( this->next != NULL ) this->next->pre = newblock ;
this->next = newblock ;
/*注意修改一些基本的field*/
newblock->len = len - pos ;
newblock->setData(data+pos,len-pos); /*赋值*/
this->len = pos ; /*完成[0,pos)的分裂*/
}
③:合并
本块合并掉下一块
bool Union() /*当下一块和本块数据之和 < maxn 的时候可以合并*/
{
block<ElemType>* nextBlock = this->next ;
if( nextBlock == NULL ) return false ;
if( nextBlock->len + this->len > maxn ) return false ;
/*合并*/
if( this->rev )
{
reverse(this->data,this->data+this->len);
this->rev = 0 ;
}
if( nextBlock->rev )
{
reverse(nextBlock->data,nextBlock->data+nextBlock->len);
nextBlock->rev = 0 ;
}
this->next = nextBlock->next ;
if( nextBlock->next != NULL ) nextBlock->next->pre = this ;
int i ;
for( i = 0 ; i < nextBlock->len ; i++) data[this->len++] = nextBlock->data[i] ;
delete nextBlock;
return true ;
}
④:删除
void del() /*delete the next block*/
{
block<ElemType> * nextBlock = this->next ;
if( nextBlock == NULL ) return ;
this->next = nextBlock->next ;
if( nextBlock->next != NULL ) nextBlock->next->pre = this ;
delete nextBlock ;
}
这里就是一个链表,节点为block,针对具体情况有不同的操作。
附个editor和反转列表完整代码(合并在一起了)
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <iostream>
#include <string>
#include <math.h>
#include <time.h>
#include <vector>
#include <queue>
#include <algorithm>
#define showArray(a,len) for( i = 0 ; i < len ; i++) printf(&