Java 实现堆栈和队列

来源:互联网 发布:二次安防用哪个网络 编辑:程序博客网 时间:2024/06/02 08:39

1.堆栈

package CareerCup;public class Stack {Node top;public Stack(){}public void push(int data){Node node = new Node(data);node.next = top;top = node;}public Node pop(){if(top!=null){Node node = top;top = top.next;return node;}return null;}}

2.队列

package CareerCup;public class Queue {Node front;Node tail;public Queue(){};public void enqueue(int data){if(front==null){front = new Node(data);tail = front;}else{Node node = new Node(data);tail.next = node;tail = node;}}public Node dequeue(){if(front!=tail){Node node = front;front = front.next;return node;}return null;}}