栈的实现
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class Stack {
ListNode head = new ListNode();
int count = 0;
public Stack() {
}
public void push(int item){
ListNode newNode = new ListNode(item);
newNode.next = head.next;
head = newNode;
count++;
}
public int pop(){
if (count<=0){
throw new RuntimeException("stack is empty");
}
ListNode p = head;
head = head.next;
count--;
return p.val;
}
public Boolean isEmpty(){
if(count<=0){
return true;
}
return false;
}
}
队列的实现
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
class Queue{
ListNode head = new ListNode();
ListNode tail = head;
int count = 0;
public Queue() {
}
public void queue(int item){
ListNode newNode = new ListNode(item);
tail.next = newNode;
tail = newNode;
}
public int dequeue(){
ListNode p = head;
head = head.next;
return p.val;
}
}