数据结构:快状链表(数组链表联合)

来源:互联网 发布:声鉴软件 编辑:程序博客网 时间:2024/05/01 13:46
#include <iostream>#define _MAX_ 10using namespace std;//块状链表。struct MyNode{    //按理说每块数据的数组长度应该是根号N到2倍的根号N之间,暂时    //我为了测试就使用100个左右的数据。    int *data;    int size;//大小。    int currentIndex;//当前下标。    MyNode *prev;    MyNode *next;    MyNode() :prev(NULL), next(NULL)    {        data = new int[_MAX_];        size = _MAX_;        currentIndex = 0;    }};class MyBlock{public:    MyBlock()    {        first = last = new MyNode();//不循环了吧。    }    void Insert(int a[],int n )    {        MyNode *p = first;        for (int i = 0; i < n; i++)        {            if (p == first)//一快还没有创建。            {                MyNode *s = new MyNode();                s->data[s->currentIndex] = a[i];//刚在第一快第一个位置。                s->currentIndex++;                s->prev = p;                p->next = s;                p = s;//p后移动。            }            else            {                p = first->next;//从开头开始找,我才可以保证我的每一块都有序,快与快之间也有序。                while (p->next != NULL)                {                    if (p->next->data[0] > a[i])                        break;                    p = p->next;//找到a[i]的位置。                }                //先插入,如果满了就拆分,满了是_MAX_(10)个元素,按一般拆分,就是5个数据。                int j;                for (j = p->currentIndex; j > 0; j--)                {                    if (p->data[j - 1] < a[i])                        break;                    p->data[j] = p->data[j - 1];//插入排序。                }                p->data[j] = a[i];                p->currentIndex++;                //判断是否满了,满了就取半拆分。                if (p->currentIndex == p->size)                {                    MyNode *s = new MyNode();                    for (j = 5; j < p->size; j++)                    {                        s->data[s->currentIndex++] = p->data[j];                    }                    p->currentIndex -= 5;                    if (p->next != NULL)                    {                        p->next->prev = s;                        s->next = p->next;                        s->prev = p;                        p->next = s;                    }                    else                    {                        s->prev = p;                        p->next = s;                        p = s;                    }                }            }        }    }    void Printf()    {        MyNode  *p = first->next;        int count = 1;        while (p != NULL)        {            cout << "第" <<count++<< "快" << "    :    ";            for (int i = 0; i < p->currentIndex; i++)            {                cout << p->data[i] << "  ";            }            cout << endl;            p = p->next;        }    }private:    MyNode *first;    MyNode *last;    //好吧,是双向循环链表。};int main(){    int a[100];    for (int i = 0; i < 100; i++)    {        a[i] = rand() % 100;    }    MyBlock mb;    mb.Insert(a,sizeof(a)/sizeof(int));    mb.Printf();}

这里写图片描述

1 0
原创粉丝点击