栈
类似于往手枪里压入子弹,先进后出。
数组实现
package com.example.data;
/**
* *@ClassName stack
* *@Author yyc
* *@Date 2020/6/15 13:46
* 使用数组来实现堆栈结构
**/
public class stackClass {
private int length;
//记录当前位置
private int topIndex;
private int[] stacklist;
//设置堆栈的长度
public void setSize(int len){
this.length=len;
stacklist=new int[len];
topIndex=0;
}
//压入数据
public void push(int v) throws Exception {
if(topIndex<=length)
{
stacklist[topIndex++]=v;
}
else
{
throw new Exception("空间已满");
}
}
//弹出数据
public int pop() throws Exception {
if(topIndex>0)
{
return stacklist[--topIndex];
}
else
throw new Exception(("已没有数据"));
}
}
链表
package com.example.data;
import java.util.Iterator;
/**
* *@ClassName Stack
* *@Author yyc
* *@Date 2020/6/15 14:08
**/
public class Stack{
public Node head;
private int length;
public Stack(){
this.head=new Node(null,null);
this.length=0;
}
public void push(Integer value)
{
Node oldNext=head.next;
if(oldNext==null)
{
head.next=new Node(value,null);
}
else
head.next=new Node(value,oldNext);
}
public Integer pop(){
Node oldNext=head.next;
if(oldNext!=null)
{
head.next=head.next.next;
return (Integer) oldNext.item;
}
else
return null;
}
}
package com.example.data;
/**
* *@ClassName Node
* *@Author yyc
* *@Date 2020/6/15 14:23
**/
public class Node<T> {
public T item;
public Node next;
public Node(T item,Node next){
this.item=item;
this.next=next;
}
}
package com.example.data;
/**
* *@ClassName Node
* *@Author yyc
* *@Date 2020/6/15 14:23
**/
public class Node<T> {
public T item;
public Node next;
public Node(T item,Node next){
this.item=item;
this.next=next;
}
}