栈表简单实现--数据结构与算法纪录片第二记

Posted qugemingzihaonan13

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了栈表简单实现--数据结构与算法纪录片第二记相关的知识,希望对你有一定的参考价值。

栈的实现:

  

package linear.stack;

import java.lang.reflect.Array;

/**
* @Description: 栈的实现
* @Auther: Weijie.Zhang
* @Date: 2018/11/2 16:56
*/
public class Stack<T> {
private final static int DEFAULT_SIZE = 10;
private T[] array;
private int count;

public Stack(int size, Class<T> type) {
count = 0;
array = (T[]) Array.newInstance(type, size);
}

public Stack(Class<T> type) {
this(DEFAULT_SIZE, type);
}

//添加元素
public T push(T value) {
array[count] = value;
count++;
return value;
}

//删除元素
public T pop() {
return array[--count];
}

//返回栈顶元素值
public T pick() {
return array[count - 1];
}

//返回栈大小
public int size() {
return count;
}

//返回栈是否为空
public Boolean isEmpty() {
return this.size() > 0 ? true : false;
}

//打印栈
public void printStack() {
if (!this.isEmpty()) {
System.out.println("空栈");
}

for (int i = size() - 1; i > 0; i--) {
System.out.print(array[i] + " ");
}
}

}

测试:
package linear.stack;

/**
* @Description: TODO
* @Auther: Weijie.Zhang
* @Date: 2018/11/2 17:14
*/
public class MainTest {
public static void main(String[] args) {
Stack<Integer> stack = new Stack(Integer.class);
stack.printStack();
for (int i = 0; i < 10; i++) {
stack.push(i + 22);
}
System.out.println(stack.size());
System.out.println(stack.pick());
stack.pop();
System.out.println(stack.size());
stack.push(10000);
stack.printStack();
}
}

技术分享图片

 























































































以上是关于栈表简单实现--数据结构与算法纪录片第二记的主要内容,如果未能解决你的问题,请参考以下文章

HDFS简单的shell操作--大数据纪录片第二记

双向链表简单实现--数据结构与算法纪录片第一记

“疑难杂症”又二记

第二记:webdriver API

RabbitMQ学习第二记:工作队列的两种分发方式,轮询分发(Round-robin)和 公平分发(Fair dispatch)

选择排序算法详解及代码实现