双指针
package com.stack;
public class MyStack {
Node head;
Node tail;
class Node{
Node pre;
String value;
Node(String value){
this.value=value;
}
@Override
public String toString() {
if (this.pre == null) {
return String.valueOf(this.value);
}
return this.pre.toString() + " <- " + this.value;
}
}
public void push(String value){
if (head==null){
head=new Node(value);
tail=head;
}else {
Node node=new Node(value);
node.pre=tail;
tail=node;
}
}
public String pop(){
if (head==null){
return null;
}
String out;
if (tail==head){
out=head.value;
tail=null;
head=null;
return out;
}
out=tail.value;
tail=tail.pre;
return out;
}
@Override
public String toString(){
return tail.toString();
}
public static void main(String[] args) {
MyStack stack = new MyStack();
stack.push("1");
stack.push("2");
stack.push("3");
stack.push("4");
String pop = stack.pop();
System.out.println(stack);
}
}
单指针
package com.stack;
public class MyStac2 {
Node tail;
class Node{
Node pre;
String value;
Node(String value){
this.value=value;
}
@Override
public String toString() {
if (this.pre == null) {
return String.valueOf(this.value);
}
return this.pre.toString() + " <- " + this.value;
}
}
public void push(String value){
if (tail==null){
tail=new Node(value);
}else {
Node node=new Node(value);
node.pre=tail;
tail=node;
}
}
public String pop(){
if (tail==null){
return null;
}
String out;
out=tail.value;
tail=tail.pre;
return out;
}
@Override
public String toString(){
return tail.toString();
}
public static void main(String[] args) {
MyStac2 stack = new MyStac2();
stack.push("1");
stack.push("2");
stack.push("3");
stack.push("4");
System.out.println(stack);
System.out.print(stack.pop());
System.out.print(stack.pop());
System.out.print(stack.pop());
System.out.print(stack.pop());
}
}