块状链表之代码剖析

本文深入剖析块状链表,解释其节点(block)的构造及基本操作,包括按指定位置分割、合并相邻块以及删除操作。提供完整的编辑器和列表反转代码示例。
摘要由CSDN通过智能技术生成

对块状链表不熟悉的请移步

块状链表解析

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 ;
    }


2.blocklist的编写

这里就是一个链表,节点为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(&
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值