class Node<E>{
E data;
Node<E> next = null;
public Node(E data){
this.data = data;
}
}
public class ListStack<E>{
Node<E> top = null;
public boolean empty(){
return top == null;
}
//头插法插入新节点,实现入栈
public void push(E data){
Node<E> newNode = new Node<E>(data);
newNode.next = top;
top = newNode;
}
public E pop(){
if(this.empty()){
return null;
}
E data = top.data;
top = top.next;
return data;
}
public E peek(){
if(empty())
return null;
return top.data;
}
}
栈数据结构实现
本文详细介绍了一种使用链表实现的栈数据结构。通过定义Node类来存储数据和指向下一个节点的引用,以及ListStack类来实现栈的基本操作,如push、pop和peek等。这种实现方式适用于需要高效进行元素入栈和出栈操作的场景。
282

被折叠的 条评论
为什么被折叠?



