首先要明白栈有什么特色,毕竟知己知彼,百战不殆,那么栈有什么特色呢:先进后出
/**
* 用链表模仿栈
*/
public class Code02 {
public static class Node{
private Integer value;
private Node next;
public Node(Integer value) {
this.value = value;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
public static class MyStack {
private Integer size;
private Node head;
private Node tail;
public MyStack() {
size = 0;
}
public MyStack(Integer size) {
this.size = size;
}
public boolean isEmpty(){
return size==0;
}
public Node push(Integer value){
Node add = new Node(value);
if(size == 0){
head = add;
tail = add;
} else {
Node next = head;
head = add;
head.next = next;
}
size++;
return head;
}
public Integer pop(){
if(isEmpty()){
return null;
}
Integer value = head.value;
head = head.next;
size--;
return value;
}
public Integer peek(){
if(isEmpty()){
return null;
}
return head.value;
}
}
public static void main(String[] args) {
MyStack stack = new MyStack();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.peek());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}
该篇博客详细介绍了如何使用链表模仿栈这一数据结构,重点在于栈的先进后出特性。通过定义Node类来创建链表节点,并在MyStack类中实现了push、pop、peek等基本操作。示例代码展示了如何初始化栈、压入元素、弹出元素以及查看栈顶元素的过程。
7038

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



