zoukankan      html  css  js  c++  java
  • 数据结构之【栈】+十进制转d进制(堆栈数组模拟)

    其实这篇文章开出来主要是水文章%%  %%

      栈——后进先出的婊

      特点:只能在某一端插入和删除的特殊的线性表

      操作:进栈——PUSH—>向栈顶插入元素

         出栈——POP——>将栈顶元素删除

      实现:

        定义一个长为n的数组,用一个top(相当于指针)指向栈顶,若top=0,则表示栈空;top=n,则表示栈满。

      进栈时top+1,出栈时top-1.  栈指针(top)在运算中永远都指向栈顶

        若top>n(n为栈的长度),则为溢出,做出错处理;若top<0,则为下溢,同样做出错处理

         【具体讲就是——进栈时——>检查栈是否已满(top是否等于n)——>不满则进栈,满则做出错处理  

         【出栈时——>检查栈是否为空(top是否等于0)——>不为空则出栈,栈空则做出错处理】

      大致实现如下:

    #dfine n 100
    
    void push(int s[],int top,int x)
    {
      if(top==n)
        cout<<"overflow";
      else
      {
        top++;
        s[top]=x;
      }
    }
    
    void pop(int s[],int top,int x)
    {
      if(top==0)
        cout<<"underflow";
      else
      {
        y=s[top];
        top--;
      }
    }
    

      

      十进制转d进制

      刷666的都坐下,基本操作

      我们用类似于堆栈数组模拟的办法来实现十进制转d进制

      【算法原理:对十进制下的n转为d进制时,有:n=(n/d)*d+n%d(好吧其实就是短除法)

      如(1348)10——>(2504)8

      ①1348/8==168 1348%8==4      ^

      ②168/8==21   168%8==0    ^  |  ^

      ③21/8==2       21%8==5          |

      ④2/8==0         2%8==2       |

      

      按着箭头方向,倒着输出结果,就是(1348)10——>(2504)8 的过程了       

      程序实现如下:

    #include<cstdlib>
    #include<iostream>
    using namespace std;
    #dfine size 100
    int a[size+1],n,d,i=0;
    int main()
    {
      cout<<"please enter a number(N) base 10:";
      cin>>n;
      cout<<endl;
      cout<<"please enter a number(d):"
      cin>>d;
       do
      {
        a[++i]=n%d;
        n=n/d;
      }
      while(n!=0);
      for(int j=i;j>=1;j--)
      {
        cout<<a[j];
      }
    
       return 0;
    }
    

      

    //栈的应用:

      1、用一个指针来记录“栈顶”;

      2、将元素入栈,然后出栈,达到倒序输出的目的;

  • 相关阅读:
    oracle 导入数据时提示只有 DBA 才能导入由其他 DBA 导出的文件
    oracle 常用语句
    android udp 无法收到数据 (模拟器中)
    android DatagramSocket send 发送数据出错
    AtCoder ABC 128E Roadwork
    AtCoder ABC 128D equeue
    AtCoder ABC 127F Absolute Minima
    AtCoder ABC 127E Cell Distance
    CodeForces 1166E The LCMs Must be Large
    CodeForces 1166D Cute Sequences
  • 原文地址:https://www.cnblogs.com/pirote-zjy/p/7744999.html
Copyright © 2011-2022 走看看