- 论坛徽章:
- 0
|
以下是我数据结构课程中的一个作业.我在Ubuntu下用g++编译后,运行会显示"段错误",但是在Win下用g++编译后,运行没有提示.我不知道我哪里出问题了.用gdb调试,程序似乎是在其中的一个FilterDown函数中中断的.但是我看不出问题.诸位帮忙看看.
- #include<iostream>
- using namespace std;
- class heap{
- public:
- heap(int size = 10):maxsize(size) , currentsize(0) { heapArray = new int[10]; }
- heap(int a[] , int size); //通过一个数组构建一个堆.
- ~heap(){delete [] heapArray;}
- int getTop(){return heapArray[0];}
- bool deletetop(); //删除堆顶
- bool insert(int data); //插入一个元素
- bool isempty() const{ return currentsize == 0; }
- bool isfull() const{ return currentsize == maxsize; }
- int sizeofheap() { return currentsize; }
- void setempty(){ currentsize = 0 ;}
-
- private:
- int *heapArray;
- int currentsize;
- int maxsize;
- void FilterDown(int p); //向下调整函数
- void FilterUp(int p ); //想上调整函数
- };
- bool heap::deletetop()
- {
- if ( currentsize == 0 )
- return false;
- heapArray[0] = heapArray[currentsize-1];
- currentsize--;
- FilterDown(0);
- return true;
- }
- bool heap::insert(int data)
- {
- if ( currentsize == maxsize )
- return false;
- heapArray[currentsize] = data;
- FilterUp(currentsize);
- currentsize++;
- return true;
- }
- void heap::FilterUp(int p)
- {
- int temp;
- int i = p;
- int j = (i - 1) / 2;
- while( j >= 0 )
- {
- if ( heapArray[i] < heapArray[j] )
- {
- temp = heapArray[i];
- heapArray[i] = heapArray[j];
- heapArray[j] = temp;
- }
- else
- break;
- i = j;
- j = (j - 1) / 2;
- }
- }
- heap::heap(int a[] , int size)
- {
- maxsize = size + 10;
- heapArray = new int[maxsize];
- heapArray = a;
- currentsize = size;
- int i = (currentsize - 2) / 2;
- while(i >= 0)
- {
- FilterDown(i--);
- }
- }
- void heap::FilterDown(int p)
- {
- int i = p;
- int j = i * 2 + 1;
- int temp;
- while ( j < currentsize )
- {
-
- if ( ( (j + 1) < currentsize ) && ( heapArray[j] > heapArray[j+1] ) )
- j++;
-
- if ( heapArray[i] > heapArray[j] )
- {
- temp = heapArray[i];
- heapArray[i] = heapArray[j];
- heapArray[j] = temp;
- }
- else
- break;
- i = j;
- j = j * 2 + 1;
- }
- }
- int main()
- {
- int a[] = {80 , 57 , 99 , 35 , 23 , 11 , 74 , 29 , 62 , 16};
- heap b(a , 10);
- b.insert(14);
- b.deletetop();
- }
复制代码 |
|