类名 Stack
构造方法 Stack):创建Stack对象
成员方法
1.public boolean isEmpty():判断栈是否为空,是返回true,否返回false
2.public int size():获取栈中元素的个数
3.public T pop():弹出栈顶元素
4.public void push(T t):向栈中压入元素t
成员变量
1.private Node head:记录首结点
2.private int N:当前栈的元素个数
1.3.2 栈的实现// 栈代码
import java.util.Iterator;
public class Stack implements Iterable{
//记录首结点
private Node head;
//栈中元素的个数
private int N;
public Stack() {
head = new Node(null,null);
N=0;
}
//判断当前栈中元素个数是否为0
public boolean isEmpty(){
return N0;
}
//把t元素压入栈
public void push(T t){
Node oldNext = head.next;
Node node = new Node(t, oldNext);
head.next = node;
//个数+1
N++;
}
//弹出栈顶元素
public T pop(){
Node oldNext = head.next;
if (oldNextnull){
return null;
}
//删除首个元素
head.next = head.next.next;
//个数-1
N–;
return oldNext.item;
}
//获取栈中元素的个数
public int size(){
return N;
}
@Override
public Iterator iterator() {
return new SIterator();
}
private class SIterator implements Iterator{
private Node n = head;
@Override
public boolean hasNext() {
return n.next!=null;
}
@Override
public T next() {
Node node = n.next;
n = n.next;
return node.item;
}
}
private class Node{
public T item;
public Node next;
public Node(T item, Node next) {
this.item = item;
this.next = next;
}
}
}
//测试代码
public class Test {
public static void main(String[] args) throws Exception {
Stack stack = new Stack<>();
stack.push(“a”);
stack.push(“b”);stack.push(“c”);
stack.push(“d”);
for (String str : stack) {
System.out.print(str+" “);
}
System.out.println(”-----------------------------");
String result = stack.pop();
System.out.println(“弹出了元素:”+result);
System.out.println(stack.size());
}
}
java数据结构栈
最新推荐文章于 2025-03-10 20:17:27 发布