2017-07-29 90 views
-2

動態初始化MinStack無法做到。爲什麼?MinStack類不給出輸出

#include<bits/stdc++.h> 
#include<iostream> 
#include<stdlib.h> 
using namespace std; 
class Stack 
{ 
    int top; 
    int length; 
    int *arr; 
public: 
     //Maximum size of Stack 

    Stack(int len) 
    { 
     top = -1; 
     length=len; 
     arr=new int[length]; 
    } //constructor 

    void push(int data); 
    int pop(); 
    bool isEmpty(); 
    bool isStackFull(); 
    int Size(); 
    void Display(); 
    int getPeek(); 

}; 

void Stack::push(int data) 
{ 
    if (isStackFull()) 
    { 
     cout << "Stack Overflow"<<endl; 
    } 
    else 
    { 
     arr[++top] = data; 
    } 
} 

int Stack::pop() 
{ 
    if (isEmpty()) 
    { 
     cout << "Stack Underflow"<<endl; 
     return 0; 
    } 
    else 
    { 
     int data = arr[top--]; 
     return data; 
    } 
} 

bool Stack::isEmpty() 
{ 
    return (top < 0); 
} 

bool Stack::isStackFull() 
{ 
    return (top == length-1); 
} 

int Stack::Size() 
{ 
    return (top +1); 
} 

int Stack::getPeek() 
{ 
    return arr[top]; 
} 

void Stack::Display() 
{ 
    for(int i=top;i!=-1;i--) 
    { 
     cout<<arr[i]<<" "; 
    } 
    cout<<endl; 
} 


class SpecialStack: public Stack 
{ 

public: 
    Stack min1; 
    SpecialStack(int len):Stack(len) 
    { 
     min1= new Stack(len); 
    } 
    int pop(); 
    void push(int x); 
    int getMin(); 
}; 
void SpecialStack::push(int x) 
{ 
    if(isEmpty()==true) 
    { 
     Stack::push(x); 
     min1.push(x); 
    } 
    else 
    { 
     Stack::push(x); 
     int y = min1.pop(); 
     min1.push(y); 
     if(x < y) 
     min1.push(x); 
     else 
     min1.push(y); 
    } 
} 

/* SpecialStack's member method to remove an element from it. This method 
removes top element from min stack also. */ 
int SpecialStack::pop() 
{ 
    int x = Stack::pop(); 
    min1.pop(); 
    return x; 
} 

int SpecialStack::getMin() 
{ 
    int x = min1.pop(); 
    min1.push(x); 
    return x; 
} 

int main() 
{ 
    SpecialStack s(3); //size of stack should be 3 
    s.push(10); 
    s.push(20); 
    s.push(30); 
    cout<<s.getMin()<<endl; 
    s.push(5); 
    cout<<s.getMin(); 
    return 0; 
} 

MinStack動態初始化無法做到。爲什麼,如何糾正這個問題。請解釋一下。

+0

抱歉再次提出同樣的問題,因爲它詢問詳細信息。 – Kamal

回答

0

SpecialStack構造函數初始化基地Stack正常,但不是min1成員。他們應該被同樣的方式處理:

SpecialStack(int len):Stack(len),min1(len) 
{ } 

當你沒有在構造函數初始化列表min1做,編譯器試圖做調用它的默認構造函數,但Stack類沒有之一。

+0

非常感謝@波佩森真的幫助了! – Kamal