Posted on 2017-03-27 15:43
为自己代言 阅读(2234)
评论(0) 编辑 收藏 所属分类:
算法/数据结构
栈的特点:后进先出,所以一个线性链表实现的栈也只能在一端操作才能满足这种特性;
/**
* @Author: zzz
* @CreateTime: 2017/3/27 14:51
* @Description:
*/
public class MyStack<T> {
private Node top;//永远指向栈顶元素
//元素个数
private int size;
/**
* 内部类,定义节点
*/
private class Node {
public T data;
public Node next;
public Node(T data, Node next) {
this.data = data;
this.next = next;
}
}
public void push(T data) {
//next 指向当前元素top,如果是第一个元素next 指向null;
Node node = new Node(data, top);
//把当前元素指向top
top = node;
size++;
}
public T pop() {
Node oldNode = top;
top = top.next;
oldNode.next = null;
//释放引用
return oldNode.data;
}
//返回栈顶的元素,但不出栈
public T peek() {
return top.data;
}
// 判断链栈是否为空栈
public boolean empty() {
return size == 0;
}
public String toString() {
// 链栈为空链栈时
if (empty())
return "[]";
else {
StringBuilder sb = new StringBuilder("[");
for (Node current = top; current != null; current = current.next) {
sb.append(current.data.toString() + ", ");
}
int len = sb.length();
return sb.delete(len - 2, len).append("]").toString();
}
}
public static void main(String[] args) throws Exception {
MyStack stack = new MyStack<String>();
for (int i = 0; i <= 10; i++) {
stack.push("111111-" + i);
}
System.out.println(stack);
System.out.println("frist pop="+stack.pop());
System.out.println("second pop="+stack.pop());
System.out.println("thrid pop="+stack.pop());
System.out.println("pop 之后的"+stack);
}
/**
* Created by zz.zhang on 2018/1/4.
*/
public class MyStack<T> {
private int DEFAULT_SIZE = 8;//定义栈的初始默认长度
private int capacity;//保存顺序栈的长度
private int size;//保存顺序栈中元素的个数
private Object[] elementData;//定义一个数组用于保存顺序栈中的元素
public MyStack() {
capacity = DEFAULT_SIZE;
elementData = new Object[capacity];
}
public MyStack(int initSize) {
capacity = 1;
while (capacity < initSize) {
capacity <<= 1;//将capacity设置成大于initSize的最小2次方
}
elementData = new Object[capacity];
}
public void push(T element) throws Exception {
elementData[size++] = element;
}
public T pop() throws Exception {
if (empty()) {
throw new IndexOutOfBoundsException("栈空,不能出栈");
}
T oldValue = (T) elementData[size - 1];
elementData[--size] = null; // 设置成null 让JVM垃圾回收
return oldValue;
}
public boolean empty() {
return size == 0;
}
//返回当前顺序栈中元素的个数
public int length() {
return size;
}
//获取栈顶元素,不会将栈顶元素删除
public T peek() throws Exception {
if (size == 0)
throw new ArrayIndexOutOfBoundsException("栈为空");
return (T) elementData[size - 1];
}
public void clear() {
for (int i = 0; i < size; i++) {
elementData[i] = null;
}
size = 0;
}
public static void main(String[] args)throws Exception{
MyStack<String> stack=new MyStack<String>(30);
for(int i=0 ;i<30;i++){
stack.push(String.valueOf(i));
}
System.out.println(stack.pop());
System.out.println(stack.peek());
}
}