前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Stack Stracture

Stack Stracture

原创
作者头像
CoffeeLand
修改2020-03-05 09:15:03
3560
修改2020-03-05 09:15:03
举报
文章被收录于专栏:CoffeeLandCoffeeLandCoffeeLand

Stack definition

stack是限定仅在表尾进行插入和删除操作的线性表

或者

stack是限定在只能在栈顶进行插入和删除操作的线性表

Stack Features

Last in First Out

Underlying principle inside the stack

stack是一个有顺序的线性表,既然是线性表,底层是数组,

Because stack是Last in first out. 因此数组的index是0最适合做栈底, 因为变化最小

Source code of the Stack


Stack class Diagram

class Stack<E> extends Vector<E>

Stack Method

Implement stack structure with Java

package com.coffeland.test;

public class Stack
{
    int Max = 5;
    int top;
    Object[] arr = new Object[5];

    Stack(int maxSize)
    {
        this.Max = maxSize;
        top = -1;
    }

    boolean push(int val)
    {
        // can not push the element into stack if the
        if (top >= (Max-1))
            return false;
        else
        {
            top = top +1;
            arr[top] = val;
            System.out.println(val + " pushed into stack");
            return true;
        }
    }

    Object pop()
    {
        if(top < 0)
            return -1;
        else
        {
            arr[top--] = null;
            return peek();
        }
    }

    Object peek()
    {
        return arr[top];
    }

    void printArr()
    {
        for(Object elem : arr)
        {
            System.out.print (elem + " ");
        }
        System.out.println("-------------------------");
    }

    public static void main(String[] args) {
        Stack s = new Stack(5);
        s.push(10);
        s.push(20);
        s.push(30);
        s.printArr();
        s.pop();
        s.printArr();
    }
}

output:

20 pushed into stack
30 pushed into stack
10 20 30 null null -------------------------
top = 1
10 20 null null null -------------------------

Process finished with exit code 0

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Stack definition
  • Stack Features
  • Underlying principle inside the stack
  • Source code of the Stack
    • Stack class Diagram
      • Stack Method
      • Implement stack structure with Java
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档