LinkedList模拟出栈入栈
原创
©著作权归作者所有:来自51CTO博客作者虾米大王的原创作品,请联系作者获取转载授权,否则将追究法律责任
package com.shrimpking.t11;
import java.util.LinkedList;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2024/9/10 11:49
*/
public class MyStack<E>
{
private LinkedList<E> list = new LinkedList<>();
//出栈
public E pop(){
return list.removeLast();
}
//压栈
public void push(E obj){
list.addLast(obj);
}
//是否有元素
public boolean empty(){
return list.isEmpty();
}
//查看元素,但不删除
public E peek(){
return list.getLast();
}
}
package com.shrimpking.t11;
/**
* Created by IntelliJ IDEA.
*
* @Author : Shrimpking
* @create 2024/9/10 11:53
*/
public class StackTest
{
public static void main(String[] args)
{
MyStack<String> ms = new MyStack<>();
ms.push("one");
ms.push("two");
ms.push("three");
System.out.println(ms.pop());
System.out.println(ms.peek());
System.out.println(ms.pop());
if(ms.empty()){
System.out.println("栈为空");
}else {
System.out.println("栈不为空");
}
}
}