1. 程式人生 > >2017級軟體工程專業《資料結構與演算法A》實驗2:棧的應用

2017級軟體工程專業《資料結構與演算法A》實驗2:棧的應用

題目:

Description

根據棧的特點,實現十進位制到其他進位制之間的轉換,具體要求如下:

(1)利用棧進行十進位制數與N進位制(如二進位制、八進位制、十六進位制)資料之間的轉換;

(2)通過順序棧記錄進位制轉換的中間結果,該順序棧有一個指示棧頂的變數top,實現棧的判空、判滿、入棧、出棧、進位制轉換等操作;

(3)順序棧類定義的參考程式碼如下:

const int MaxStackSize=10; //棧最大容量(根據問題修改該值)

class SeqStack {

         DataType StackList[MaxStackSize];

         int top;   //指示棧頂的變數

 public:

    SeqStack( );  //建構函式

    bool IsEmpty( );   //判斷棧空

    bool IsFull( ) ;   //判斷棧滿

    void Push(const DataType x);   //入棧

    DataType Pop( );   //出棧

    void Clear( ) ;   //置棧空

    void Conversion(int M, int N);   //進位制轉換,並輸出結果

}; //SeqStack

Input

該題目有多組測試資料,每組測試資料佔一行。例如:M N,其中M(1≤M≤10000)是待轉換的十進位制數,N(2≤N≤9)表示某種進位制。當輸入-1 -1時結束。

Output

輸出對應進位制的數值,每條資料佔一行。

Sample Input

1 9
9999 7
7 2
10000 2
156 8
15 5
10000 9
1234 6
780 4
6143 3
-1 -1

Sample Output

1
41103
111
10011100010000
234
30
14641
5414
30030
22102112

題解:

#include<iostream>
using namespace std;
 
const int MaxStackSize = 15;
 
class SeqStack
{
    int StackList[MaxStackSize];
    int top;
public:
    SeqStack();
    bool isEmpty();
    bool isFull();
    void Push(const int x);
    int Pop();
    void Clear();
    void Conversion(int m,int n);
};
 
SeqStack::SeqStack()
{
    top = -1;
}
 
bool SeqStack::isEmpty()
{
    if(top==-1)
        return 1;
    else
        return 0;
}
 
bool SeqStack::isFull()
{
    if(top==MaxStackSize)
        return 1;
    else
        return 0;
}
 
void SeqStack::Push(const int x)
{
    StackList[++top]=x;
}
 
int SeqStack::Pop()
{
    if(!isEmpty())
    {
        return StackList[top--];
    }
}
 
void SeqStack::Clear()
{
    top=-1;
}
 
void SeqStack::Conversion(int m,int n)
{
    while(m!=0)
    {
        Push(m % n);
        m=m/n;
    }
}
 
int main()
{
    int m,n;
    SeqStack seqstack;
    while(cin>>m>>n)
    {
        if(m==-1 && n==-1)
            break;
        seqstack.Conversion(m,n);
        while(!seqstack.isEmpty())
        {
            cout<<seqstack.Pop();
        }
        seqstack.Clear();
        cout<<endl;
    }
}