1 栈的描述
栈是一个先入后出(FILO-First In Last Out)的有序列表。
栈(stack)是限制线性表中元素的插入和删除只能在线性表的同一端进行的一种特殊线性表。允许插入和删除的一端,为变化的一端,称为栈顶(Top),另一端为固定的一端,称为栈底(Bottom)。
根据栈的定义可知,最先放入栈中元素在栈底,最后放入的元素在栈顶,而删除元素刚好相反,最后放入的元素最先删除,最先放入的元素最后删除
2 出栈(pop)和入栈(push)的概念
3 栈的实现
package stack;
public class LinkStact<T> {
private Node<T> top;
/**
* 返回节点是否为空
* @return
*/
public boolean isEmpty(){
return top == null;
}
/**
* 进栈,创建一个节点,把该节点放到一个个位置
* @param value
*/
public void push(T value){
Node node = new Node(value, top);
top = node;
}
/**
* 出
*/
public T pop(){
if (isEmpty())
{
throw new RuntimeException("栈已经为空!");
}
Node<T> temp = top;
top = top.getNext();
return temp.getData();
}
public void show(){
if (isEmpty())
{
System.out.println("栈已经为空!");
return;
}
Node node = top;
System.out.println("栈内的数据为: ");
while (node != null){
System.out.print(node.getData() + " ");
node = node.getNext();
}
System.out.println();
}
/**
* 测试栈
* @param args
*/
public static void main(String[] args) {
LinkStact<Integer> stact = new LinkStact();
stact.push(1);
// stact.push(2);
// stact.push(3);
// stact.push(4);
// stact.push(5);
//stact.show();
System.out.println(stact.pop());
stact.push(2);
stact.push(3);
stact.show();
System.out.println(stact.pop());
System.out.println(stact.pop());
stact.show();
}
}
/**
* 节点class
*/
class Node<T>{
private T data;
private Node<T> next;
public Node() {
}
public Node(T data, Node next) {
this.data = data;
this.next = next;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
4 java集合中的栈
java.util.Stack