栈单链表实现:没有长度限制,并且出栈和入栈速度都很快
- public class LinkedList {
- private class Data{
- private Object obj;
- private Data next = null;
- Data(Object obj){
- this.obj = obj;
- }
- }
- private Data first = null;
- public void insertFirst(Object obj){
- Data data = new Data(obj);
- data.next = first;
- first = data;
- }
- public Object deleteFirst() throws Exception{
- if(first == null)
- throw new Exception("empty!");
- Data temp = first;
- first = first.next;
- return temp.obj;
- }
- public void display(){
- if(first == null)
- System.out.println("empty");
- System.out.print("top -> bottom : | ");
- Data cur = first;
- while(cur != null){
- System.out.print(cur.obj.toString() + " | ");
- cur = cur.next;
- }
- System.out.print("\n");
- }
- }
- public class LinkedListStack {
- private LinkedList ll = new LinkedList();
- public void push(Object obj){
- ll.insertFirst(obj);
- }
- public Object pop() throws Exception{
- return ll.deleteFirst();
- }
- public void display(){
- ll.display();
- }
- public static void main(String[] args) throws Exception{
- LinkedListStack lls = new LinkedListStack();
- lls.push(1);
- lls.push(2);
- lls.push(3);
- lls.display();
- System.out.println(lls.pop());
- lls.display();
- }
- }
- top -> bottom : | 3 | 2 | 1 |
- 3
- top -> bottom : | 2 | 1 |
数据项入栈和出栈的时间复杂度都为常数O(1)
队列双端链表实现:
- public class FirstLastList {
- private class Data{
- private Object obj;
- private Data next = null;
- Data(Object obj){
- this.obj = obj;
- }
- }
- private Data first = null;
- private Data last = null;
- public void insertFirst(Object obj){
- Data data = new Data(obj);
- if(first == null)
- last = data;
- data.next = first;
- first = data;
- }
- public Object deleteFirst() throws Exception{
- if(first == null)
- throw new Exception("empty");
- Data temp = first;
- if(first.next == null)
- last = null;
- first = first.next;
- return temp.obj;
- }
- public void display(){
- if(first == null)
- System.out.println("empty");
- System.out.print("first -> last : | ");
- Data cur = first;
- while(cur != null){
- System.out.print(cur.obj.toString() + " | ");
- cur = cur.next;
- }
- System.out.print("\n");
- }
- }
- public class FirstLastListQueue {
- private FirstLastList fll = new FirstLastList();
- public void push(Object obj){
- fll.insertLast(obj);
- }
- public Object pop() throws Exception{
- return fll.deleteFirst();
- }
- public void display(){
- fll.display();
- }
- public static void main(String[] args) throws Exception{
- FirstLastListQueue fllq = new FirstLastListQueue();
- fllq.push(1);
- fllq.push(2);
- fllq.push(3);
- fllq.display();
- System.out.println(fllq.pop());
- fllq.display();
- fllq.push(4);
- fllq.display();
- }
- }
- first -> last : | 1 | 2 | 3 |
- 1
- first -> last : | 2 | 3 |
- first -> last : | 2 | 3 | 4 |
长度不受限制并且插入和删除的时间复杂度都为O(1)