【資料結構】 棧實現 十進位到八進位的轉化,資料結構十進位

來源:互聯網
上載者:User

【資料結構】 棧實現 十進位到八進位的轉化,資料結構十進位



1.利用棧的基本操作

代碼實現如下



#ifndef _SEQSTACK_H#define _SEQSTACK_H#include<iostream>#include<assert.h>using namespace std;typedef int ElemType;#define STACK_INIT_SIZE 20typedef struct Stack{     ElemType *base;     int       top;     int       capacity;}Stack;void ConverSeq(int n);bool IsFull(Stack *st);bool IsEmpty(Stack *st);void InitStack(Stack *st);bool Push(Stack *st, ElemType x);bool Pop(Stack *st, ElemType *v);bool Pop(Stack *st);#endif

bool IsFull(Stack *st){return st->top >= st->capacity;}bool IsEmpty(Stack *st){return st->top == 0;}void InitStack(Stack *st){st->base = (ElemType *)malloc(sizeof(ElemType)*STACK_INIT_SIZE);assert(st->base != NULL);st->capacity = STACK_INIT_SIZE;st->top = 0;}void ConverSeq(int n){Stack s;   //定義一個棧int x = 0;   //x用於儲存餘數InitStack(&s);while (n > 0)   //輾轉相除{x = n % 8;Push(&s, x);n /= 8;}while (!IsEmpty(&s))  //輸出{Pop(&s, &x);cout << x;}}bool Push(Stack *st, ElemType x){if (IsFull(st)){cout << "棧已滿," << x << "不能入棧!" << endl;return false;}st->base[st->top++] = x;return true;}bool Pop(Stack *st){if (IsEmpty(st)){cout << "棧以空,不能出棧!" << endl;return false;}st->top--;return true;}bool Pop(Stack *st, ElemType *v){if (IsEmpty(st)){cout << "棧以空,不能出棧!" << endl;return false;}*v = st->base[--st->top];return true;}




2數組實現

#include <stdio.h>  #include <stdlib.h>  #include <malloc.h>  #define STACKSIZE 100  typedef int ElemType;   typedef struct   {      ElemType stack[STACKSIZE];      int top;  }SeqStack;  void Conversion(int N);  



void Conversion(int N){int stack[STACKSIZE], top;top = 0;do{stack[top] = N % 8;top++;N /= 8;} while (N != 0);cout<<"轉換後的八進位為:";while (top > 0){top--;cout<<stack[top];}cout<<endl;}


3.鏈表實現

#include <stdio.h>  #include <stdlib.h>  #include <malloc.h>  #include <string.h>  typedef char ElemType;  typedef struct node  {      ElemType data;      struct node *next;  }LStackNode,*LinkStack;    void Conversion(int N);




void Conversion(int N)  {      LStackNode *p,*top = NULL;      do      {          p = (LinkStack)malloc(sizeof(LStackNode));          p->data = N%8;          p->next = top;          top = p;          N /= 8;      }while(N != 0);     cout<<"數制轉換成八位元:";      while(top != NULL)      {          p = top;          cout<<p->data;          top = top->next;          free(p);      }      cout<<endl;  }


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.