栈01:实现栈的3中方式: 数组,链表和容器

来源:互联网 发布:怎么快速成为淘宝达人 编辑:程序博客网 时间:2024/06/10 02:17

1 利用数组实现栈

package com.stack;

/**
* 栈是线性表的特例
* 利用数组实现
* 如何保证倒序取:数组倒着取
* 栈底和栈顶
* Created by weideliang on 2016/10/14.
*/
public class Stack01<T> {
private Object[] array;
private int defaultCapacity = 20;
private int capacity;
private int size;

public Stack01(){
this.init(defaultCapacity);
}

public Stack01(int capacity){
this.init(capacity);
}

private void init(int capacity){
this.array = new Object[capacity];
this.capacity = capacity;
this.size = 0;
}

/**
* 入栈
*/
public void push(T element){
if(size >= capacity){
throw new RuntimeException("栈已满");
}
array[size++] = element;
}

public void pushAll(T[] elements){
for (T element : elements) {
this.push(element);
}
}

/**
* 出栈
*/
public T pop(){
if(0 == size){
throw new RuntimeException("栈中没有数据");
}
return (T)array[--size];
}

public T peek(){
if(0 == size){
throw new RuntimeException("栈中没有数据");
}
return (T)array[size - 1];
}

/**
* 判断是否为空
* @return
*/
public boolean isEmpty(){
return size == 0;
}

public static void main(String[] args) {
Stack01<String> stack01 = new Stack01<>();
stack01.push("aa");
stack01.push("bb");
System.out.println(stack01.isEmpty());
System.out.println(stack01.pop());
System.out.println(stack01.pop());
System.out.println(stack01.isEmpty());
}
}
2 使用链表实现栈
package com.stack;

import com.linearlist.Node;
import com.sun.xml.internal.ws.model.RuntimeModelerException;

/**
* 利用链表实现栈
* 插入和删除的一段叫栈顶
* Created by weideliang on 2016/10/14.
*/
public class Stack02<T> {
private Node top;
private int size;

public Stack02(){
this.size = 0;
}
public Stack02(T element){
top = new Node(element, null);
this.size++;
}

/**
* 新结点就是top,旧结点跟在新节点的后面
* @param element
*/
public void push(T element){
top = new Node(element, top);
size++;
}

/**
* 出栈:取出并删除
* @return
*/
public T pop(){
if(this.size == 0){
throw new RuntimeModelerException("队列已空");
}
T newTop = (T)top.data();
this.size--;
top = top.next();
return newTop;
}

/**
* 只取出,不删除
* @return
*/
public String peep(){
return (String) top.data();
}

/**
* 判断是否为空
* @return
*/
public boolean isEmpty(){
return this.size == 0;
}

public static void main(String[] args) {
Stack02 stack02 = new Stack02();
stack02.push("str1");
stack02.push("str2");
stack02.push("str3");

// System.out.println(stack02.isEmpty());
System.out.println(stack02.peep());
// System.out.println(stack02.pop());
// System.out.println(stack02.pop());
// System.out.println(stack02.pop());
// System.out.println(stack02.isEmpty());
}
}
3 利用容器实现栈
0 0
原创粉丝点击