順序棧實現數制的轉換


此例為十進制N轉換為其它進制

1.順序棧的存儲結構

typedef struct{
  ElemType data[MAXSIZE];//為順序棧分配最大容量的內存
  int top;  //指向棧頂
}SqStack;
View Code

2.初始化棧

void Initstack(SqStack &S)
{
    if(!S.data) exit(-1);
    S.top = 0;
}
View Code

3.入棧

Status Push(SqStack &S,ElemType e)
{
    if(S.top==MAXSIZE) return ERROR;
    S.data[S.top++] = e;
    return OK;
}
View Code

4.出棧

Status Pop(SqStack &S)
{
   if(S.top<=0) return ERROR;
   S.top--;
   return OK;
}
View Code

5.獲得棧頂元素

void getTop(SqStack S,ElemType &e)
{
    if(S.top==0) printf("棧空了!!");
    e = S.data[S.top-1];
}
View Code

6.進制轉換

void Convertion(SqStack &S)
{
    int n,r;
    printf("輸入要轉換進制的數:\n");
    scanf("%d",&n);
    printf("輸入要轉換的進制:\n");
    scanf("%d",&r);
    while(n)
    {
        Push(S,n%r);
        n/=r;
    }
    while(S.top)
    {
        ElemType e;
        getTop(S,e);
        Pop(S);
        printf("%d",e);
    }
    printf("\n");
}
View Code

7.遍歷

void traverse(SqStack S)
{
    printf("進制轉換結果:\n");
    for(int i=S.top-1;i>=0;i--)
    {
        printf("%d",S.data[i]);
    }
    printf("\n");
}
View Code

8.全部代碼(這里就整合為一個了)

#include<stdio.h>
#include<stdlib.h>

#define MAXSIZE 100
#define ERROR 0
#define OK 1

typedef int Status;
typedef int ElemType;

typedef struct{
  ElemType data[MAXSIZE];//為順序棧分配最大容量的內存
  int top;  //指向棧頂
}SqStack;

void Initstack(SqStack &S)
{
    if(!S.data) exit(-1);
    S.top = 0;
}

Status Push(SqStack &S,ElemType e)
{
    if(S.top==MAXSIZE) return ERROR;
    S.data[S.top++] = e;
    return OK;
}

Status Pop(SqStack &S)
{
   if(S.top<=0) return ERROR;
   S.top--;
   return OK;
}
void getTop(SqStack S,ElemType &e)
{
    if(S.top==0) printf("棧空了!!");
    e = S.data[S.top-1];
}
void Convertion(SqStack &S)
{
    int n,r;
    printf("輸入要轉換進制的數:\n");
    scanf("%d",&n);
    printf("輸入要轉換的進制:\n");
    scanf("%d",&r);
    while(n)
    {
        Push(S,n%r);
        n/=r;
    }
    while(S.top)
    {
        ElemType e;
        getTop(S,e);
        Pop(S);
        printf("%d",e);
    }
    printf("\n");
}
void traverse(SqStack S)
{
    printf("進制轉換結果:\n");
    for(int i=S.top-1;i>=0;i--)
    {
        printf("%d",S.data[i]);
    }
    printf("\n");
}


int main()
{
    SqStack S;

    Initstack(S);

    Convertion(S);

   //我看了幾個博客,都是用上面的方法,下面這個也可以
   //traverse(S);//這兩個函數只能用一個
    return 0;
}
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM