package stack;
import java.util.Iterator;
/**
* @Author zhw
* Version 1.0
* @Description LinkStack
* Date 2021/8/15 14:12
**/
public class LinkStack<T> implements Iterable<T>{
//记录头结点
private Node head;
//记录链表的长度
private int N;
private class Node{
T item;
Node next;
public Node(T item,Node node){
this.item=item;
this.next=node;
}
}
public LinkStack(){
head=new Node(null,null);
this.N=0;
}
//判断栈是否为空
public boolean isEmpty(){
return N==0;
}
//获取栈中元素的个数
public int size(){
return N;
}
//压栈
public void push(T t){
Node node = new Node(t, head.next);
head.next=node;
N++;
}
//弹栈
public T pop(){
if (head.next==null){
return null;
}
Node node = head.next;
head.next=node.next;
N--;
return node.item;
}
@Override
public Iterator<T> iterator() {
return new SIterator();
}
private class SIterator implements Iterator<T>{
private Node n;
public SIterator(){
this.n=head;
}
@Override
public boolean hasNext() {
return n.next!=null;
}
@Override
public T next() {
n=n.next;
return n.item;
}
}
}
数据结构-Java-链栈
最新推荐文章于 2024-08-08 21:53:48 发布