【code】java栈和队列实现

本文详细介绍了四种数据结构的Java实现:顺序栈与链式栈、顺序队列与循环队列及链式队列,并通过示例代码展示了每种数据结构的基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

顺序栈的实现

Java代码  收藏代码
  1. import java.util.Arrays;  
  2. public class SequenceStack<T>  
  3. {  
  4.     private int DEFAULT_SIZE = 10;  
  5.     //保存数组的长度。  
  6.     private int capacity;  
  7.     //定义当底层数组容量不够时,程序每次增加的数组长度  
  8.     private int capacityIncrement = 0;  
  9.     //定义一个数组用于保存顺序栈的元素  
  10.     private Object[] elementData;  
  11.     //保存顺序栈中元素的当前个数  
  12.     private int size = 0;  
  13.     //以默认数组长度创建空顺序栈  
  14.     public SequenceStack()  
  15.     {  
  16.         capacity = DEFAULT_SIZE;  
  17.         elementData = new Object[capacity];  
  18.     }  
  19.     //以一个初始化元素来创建顺序栈  
  20.     public SequenceStack(T element)  
  21.     {  
  22.         this();  
  23.         elementData[0] = element;  
  24.         size++;  
  25.     }  
  26.     /** 
  27.      * 以指定长度的数组来创建顺序栈 
  28.      * @param element 指定顺序栈中第一个元素 
  29.      * @param initSize 指定顺序栈底层数组的长度 
  30.      */  
  31.     public SequenceStack(T element , int initSize)  
  32.     {  
  33.         this.capacity = initSize;  
  34.         elementData = new Object[capacity];  
  35.         elementData[0] = element;  
  36.         size++;  
  37.     }  
  38.     /** 
  39.      * 以指定长度的数组来创建顺序栈 
  40.      * @param element 指定顺序栈中第一个元素 
  41.      * @param initSize 指定顺序栈底层数组的长度 
  42.      * @param capacityIncrement 指定当顺序栈底层数组的长度不够时,底层数组每次增加的长度 
  43.      */  
  44.     public SequenceStack(T element , int initSize  
  45.         , int capacityIncrement)  
  46.     {  
  47.         this.capacity = initSize;  
  48.         this.capacityIncrement = capacityIncrement;  
  49.         elementData = new Object[capacity];  
  50.         elementData[0] = element;  
  51.         size++;  
  52.     }  
  53.     //获取顺序栈的大小  
  54.     public int length()  
  55.     {  
  56.         return size;  
  57.     }  
  58.     //入栈  
  59.     public void push(T element)  
  60.     {  
  61.         ensureCapacity(size + 1);  
  62.         elementData[size++] = element;  
  63.     }  
  64.     //很麻烦,而且性能很差  
  65.     private void ensureCapacity(int minCapacity)  
  66.     {  
  67.         //如果数组的原有长度小于目前所需的长度  
  68.         if (minCapacity > capacity)  
  69.         {  
  70.             if (capacityIncrement > 0)  
  71.             {  
  72.                 while (capacity < minCapacity)  
  73.                 {  
  74.                     //不断地将capacity长度加capacityIncrement,  
  75.                     //直到capacity大于minCapacity为止  
  76.                     capacity += capacityIncrement;  
  77.                 }  
  78.             }  
  79.             else  
  80.             {  
  81.                 //不断地将capacity * 2,直到capacity大于minCapacity为止  
  82.                 while (capacity < minCapacity)  
  83.                 {  
  84.                     capacity <<= 1;  
  85.                 }  
  86.             }  
  87.             elementData = Arrays.copyOf(elementData , capacity);  
  88.         }  
  89.     }  
  90.     //出栈  
  91.     public T pop()  
  92.     {  
  93.         T oldValue = (T)elementData[size - 1];  
  94.         //释放栈顶元素  
  95.         elementData[--size] = null;   
  96.         return oldValue;  
  97.     }  
  98.     //返回栈顶元素,但不删除栈顶元素  
  99.     public T peek()  
  100.     {  
  101.         return (T)elementData[size - 1];  
  102.     }  
  103.     //判断顺序栈是否为空栈  
  104.     public boolean empty()  
  105.     {  
  106.         return size == 0;  
  107.     }  
  108.     //清空顺序栈  
  109.     public void clear()  
  110.     {  
  111.         //将底层数组所有元素赋为null  
  112.         Arrays.fill(elementData , null);  
  113.         size = 0;  
  114.     }  
  115.     public String toString()  
  116.     {  
  117.         if (size == 0)  
  118.         {  
  119.             return "[]";  
  120.         }  
  121.         else  
  122.         {  
  123.             StringBuilder sb = new StringBuilder("[");  
  124.             for (int i = size - 1  ; i > -1 ; i-- )  
  125.             {  
  126.                 sb.append(elementData[i].toString() + ", ");  
  127.             }  
  128.             int len = sb.length();  
  129.             return sb.delete(len - 2 , len).append("]").toString();  
  130.         }  
  131.     }  
  132.       
  133.     public static void main(String[] args)   
  134.     {  
  135.         SequenceStack<String> stack =  
  136.             new SequenceStack<String>();  
  137.         //不断地入栈  
  138.         stack.push("aaaa");  
  139.         stack.push("bbbb");  
  140.         stack.push("cccc");  
  141.         stack.push("dddd");  
  142.         System.out.println(stack);  
  143.         //访问栈顶元素  
  144.         System.out.println("访问栈顶元素:" + stack.peek());  
  145.         //弹出一个元素  
  146.         System.out.println("第一次弹出栈顶元素:" + stack.pop());  
  147.         //再次弹出一个元素  
  148.         System.out.println("第二次弹出栈顶元素:" + stack.pop());  
  149.         System.out.println("两次pop之后的栈:" + stack);  
  150.     }  
  151. }  

 

链式栈的实现

 

Java代码  收藏代码
  1. public class LinkStack<T>  
  2. {  
  3.     //定义一个内部类Node,Node实例代表链栈的节点。  
  4.     private class Node  
  5.     {  
  6.         //保存节点的数据  
  7.         private T data;  
  8.         //指向下个节点的引用  
  9.         private Node next;  
  10.         //无参数的构造器  
  11.         public Node()  
  12.         {  
  13.         }  
  14.         //初始化全部属性的构造器  
  15.         public Node(T data , Node next)  
  16.         {  
  17.             this.data = data;  
  18.             this.next = next;  
  19.         }  
  20.     }  
  21.     //保存该链栈的栈顶元素  
  22.     private Node top;  
  23.     //保存该链栈中已包含的节点数  
  24.     private int size;  
  25.     //创建空链栈  
  26.     public LinkStack()  
  27.     {  
  28.         //空链栈,top的值为null  
  29.         top = null;  
  30.     }  
  31.     //以指定数据元素来创建链栈,该链栈只有一个元素  
  32.     public LinkStack(T element)  
  33.     {  
  34.         top = new Node(element , null);  
  35.         size++;  
  36.     }  
  37.     //返回链栈的长度     
  38.     public int length()  
  39.     {  
  40.         return size;  
  41.     }  
  42.     //进栈  
  43.     public void push(T element)  
  44.     {  
  45.         //让top指向新创建的元素,新元素的next引用指向原来的栈顶元素  
  46.         top = new Node(element , top);  
  47.         size++;  
  48.     }  
  49.     //出栈  
  50.     public T pop()  
  51.     {  
  52.         Node oldTop = top;  
  53.         //让top引用指向原栈顶元素的下一个元素  
  54.         top = top.next;  
  55.         //释放原栈顶元素的next引用  
  56.         oldTop.next = null;  
  57.         size--;  
  58.         return oldTop.data;  
  59.     }  
  60.     //访问栈顶元素,但不删除栈顶元素  
  61.     public T peek()  
  62.     {  
  63.         return top.data;  
  64.     }  
  65.     //判断链栈是否为空栈  
  66.     public boolean empty()  
  67.     {  
  68.         return size == 0;  
  69.     }  
  70.     //清空链栈  
  71.     public void clear()  
  72.     {  
  73.         //将底层数组所有元素赋为null  
  74.         top = null;  
  75.         size = 0;  
  76.     }  
  77.     public String toString()  
  78.     {  
  79.         //链栈为空链栈时  
  80.         if (empty())  
  81.         {  
  82.             return "[]";  
  83.         }  
  84.         else  
  85.         {  
  86.             StringBuilder sb = new StringBuilder("[");  
  87.             for (Node current = top ; current != null  
  88.                 ; current = current.next )  
  89.             {  
  90.                 sb.append(current.data.toString() + ", ");  
  91.             }  
  92.             int len = sb.length();  
  93.             return sb.delete(len - 2 , len).append("]").toString();  
  94.         }  
  95.     }  
  96.       
  97.     public static void main(String[] args)   
  98.     {  
  99.         LinkStack<String> stack =  
  100.             new LinkStack<String>();  
  101.         //不断地入栈  
  102.         stack.push("aaaa");  
  103.         stack.push("bbbb");  
  104.         stack.push("cccc");  
  105.         stack.push("dddd");  
  106.         System.out.println(stack);  
  107.         //访问栈顶元素  
  108.         System.out.println("访问栈顶元素:" + stack.peek());  
  109.         //弹出一个元素  
  110.         System.out.println("第一次弹出栈顶元素:" + stack.pop());  
  111.         //再次弹出一个元素  
  112.         System.out.println("第二次弹出栈顶元素:" + stack.pop());  
  113.         System.out.println("两次pop之后的栈:" + stack);  
  114.     }  
  115. }  

 

顺序队列的实现

 

Java代码  收藏代码
  1. import java.util.Arrays;  
  2. public class SequenceQueue<T>  
  3. {  
  4.     private int DEFAULT_SIZE = 10;  
  5.     //保存数组的长度。  
  6.     private int capacity;  
  7.     //定义一个数组用于保存顺序队列的元素  
  8.     private Object[] elementData;  
  9.     //保存顺序队列中元素的当前个数  
  10.     private int front = 0;  
  11.     private int rear = 0;  
  12.     //以默认数组长度创建空顺序队列  
  13.     public SequenceQueue()  
  14.     {  
  15.         capacity = DEFAULT_SIZE;  
  16.         elementData = new Object[capacity];  
  17.     }  
  18.     //以一个初始化元素来创建顺序队列  
  19.     public SequenceQueue(T element)  
  20.     {  
  21.         this();  
  22.         elementData[0] = element;  
  23.         rear++;  
  24.     }  
  25.     /** 
  26.      * 以指定长度的数组来创建顺序队列 
  27.      * @param element 指定顺序队列中第一个元素 
  28.      * @param initSize 指定顺序队列底层数组的长度 
  29.      */  
  30.     public SequenceQueue(T element , int initSize)  
  31.     {  
  32.         this.capacity = initSize;  
  33.         elementData = new Object[capacity];  
  34.         elementData[0] = element;  
  35.         rear++;  
  36.     }  
  37.     //获取顺序队列的大小  
  38.     public int length()  
  39.     {  
  40.         return rear - front;  
  41.     }  
  42.     //插入队列  
  43.     public void add(T element)  
  44.     {  
  45.         if (rear > capacity - 1)  
  46.         {  
  47.             throw new IndexOutOfBoundsException("队列已满的异常");  
  48.         }  
  49.         elementData[rear++] = element;  
  50.     }  
  51.     //移除队列  
  52.     public T remove()  
  53.     {  
  54.         if (empty())  
  55.         {  
  56.             throw new IndexOutOfBoundsException("空队列异常");  
  57.         }  
  58.         //保留队列的rear端的元素的值  
  59.         T oldValue = (T)elementData[front];  
  60.         //释放队列的rear端的元素  
  61.         elementData[front++] = null;   
  62.         return oldValue;  
  63.     }  
  64.     //返回队列顶元素,但不删除队列顶元素  
  65.     public T element()  
  66.     {  
  67.         if (empty())  
  68.         {  
  69.             throw new IndexOutOfBoundsException("空队列异常");  
  70.         }  
  71.         return (T)elementData[front];  
  72.     }  
  73.     //判断顺序队列是否为空队列  
  74.     public boolean empty()  
  75.     {  
  76.         return rear == front;  
  77.     }  
  78.     //清空顺序队列  
  79.     public void clear()  
  80.     {  
  81.         //将底层数组所有元素赋为null  
  82.         Arrays.fill(elementData , null);  
  83.         front = 0;  
  84.         rear = 0;  
  85.     }  
  86.     public String toString()  
  87.     {  
  88.         if (empty())  
  89.         {  
  90.             return "[]";  
  91.         }  
  92.         else  
  93.         {  
  94.             StringBuilder sb = new StringBuilder("[");  
  95.             for (int i = front  ; i < rear ; i++ )  
  96.             {  
  97.                 sb.append(elementData[i].toString() + ", ");  
  98.             }  
  99.             int len = sb.length();  
  100.             return sb.delete(len - 2 , len).append("]").toString();  
  101.         }  
  102.     }  
  103.     public static void main(String[] args)  
  104.     {  
  105.         SequenceQueue<String> queue = new SequenceQueue<String>();  
  106.         //依次将4个元素加入队列  
  107.         queue.add("aaaa");  
  108.         queue.add("bbbb");  
  109.         queue.add("cccc");  
  110.         queue.add("dddd");  
  111.         System.out.println(queue);  
  112.         System.out.println("访问队列的front端元素:"   
  113.             + queue.element());  
  114.         System.out.println("移除队列的front端元素:"   
  115.             + queue.remove());  
  116.         System.out.println("移除队列的front端元素:"   
  117.             + queue.remove());  
  118.         System.out.println("两次调用remove方法后的队列:"   
  119.             + queue);  
  120.   
  121.     }  
  122. }  

 

循环队列的实现

 

Java代码  收藏代码
  1. import java.util.Arrays;  
  2. public class LoopQueue<T>  
  3. {  
  4.     private int DEFAULT_SIZE = 10;  
  5.     //保存数组的长度。  
  6.     private int capacity;  
  7.     //定义一个数组用于保存循环队列的元素  
  8.     private Object[] elementData;  
  9.     //保存循环队列中元素的当前个数  
  10.     private int front = 0;  
  11.     private int rear = 0;  
  12.     //以默认数组长度创建空循环队列  
  13.     public LoopQueue()  
  14.     {  
  15.         capacity = DEFAULT_SIZE;  
  16.         elementData = new Object[capacity];  
  17.     }  
  18.     //以一个初始化元素来创建循环队列  
  19.     public LoopQueue(T element)  
  20.     {  
  21.         this();  
  22.         elementData[0] = element;  
  23.         rear++;  
  24.     }  
  25.     /** 
  26.      * 以指定长度的数组来创建循环队列 
  27.      * @param element 指定循环队列中第一个元素 
  28.      * @param initSize 指定循环队列底层数组的长度 
  29.      */  
  30.     public LoopQueue(T element , int initSize)  
  31.     {  
  32.         this.capacity = initSize;  
  33.         elementData = new Object[capacity];  
  34.         elementData[0] = element;  
  35.         rear++;  
  36.     }  
  37.     //获取循环队列的大小  
  38.     public int length()  
  39.     {  
  40.         if (empty())  
  41.         {  
  42.             return 0;  
  43.         }  
  44.         return rear > front ? rear - front   
  45.             : capacity - (front - rear);  
  46.     }  
  47.     //插入队列  
  48.     public void add(T element)  
  49.     {  
  50.         if (rear == front   
  51.             && elementData[front] != null)  
  52.         {  
  53.             throw new IndexOutOfBoundsException("队列已满的异常");  
  54.         }  
  55.         elementData[rear++] = element;  
  56.         //如果rear已经到头,那就转头  
  57.         rear = rear == capacity ? 0 : rear;  
  58.     }  
  59.     //移除队列  
  60.     public T remove()  
  61.     {  
  62.         if (empty())  
  63.         {  
  64.             throw new IndexOutOfBoundsException("空队列异常");  
  65.         }  
  66.         //保留队列的rear端的元素的值  
  67.         T oldValue = (T)elementData[front];  
  68.         //释放队列的rear端的元素  
  69.         elementData[front++] = null;   
  70.         //如果front已经到头,那就转头  
  71.         front = front == capacity ? 0 : front;  
  72.         return oldValue;  
  73.     }  
  74.     //返回队列顶元素,但不删除队列顶元素  
  75.     public T element()  
  76.     {  
  77.         if (empty())  
  78.         {  
  79.             throw new IndexOutOfBoundsException("空队列异常");  
  80.         }  
  81.         return (T)elementData[front];  
  82.     }  
  83.     //判断循环队列是否为空队列  
  84.     public boolean empty()  
  85.     {  
  86.         //rear==front且rear处的元素为null  
  87.         return rear == front   
  88.             && elementData[rear] == null;  
  89.     }  
  90.     //清空循环队列  
  91.     public void clear()  
  92.     {  
  93.         //将底层数组所有元素赋为null  
  94.         Arrays.fill(elementData , null);  
  95.         front = 0;  
  96.         rear = 0;  
  97.     }  
  98.     public String toString()  
  99.     {  
  100.         if (empty())  
  101.         {  
  102.             return "[]";  
  103.         }  
  104.         else  
  105.         {  
  106.             //如果front < rear,有效元素就是front到rear之间的元素  
  107.             if (front < rear)  
  108.             {  
  109.                 StringBuilder sb = new StringBuilder("[");  
  110.                 for (int i = front  ; i < rear ; i++ )  
  111.                 {  
  112.                     sb.append(elementData[i].toString() + ", ");  
  113.                 }  
  114.                 int len = sb.length();  
  115.                 return sb.delete(len - 2 , len).append("]").toString();  
  116.             }  
  117.             //如果front >= rear,有效元素为front->capacity之间、0->front之间的  
  118.             else  
  119.             {  
  120.                 StringBuilder sb = new StringBuilder("[");  
  121.                 for (int i = front  ; i < capacity ; i++ )  
  122.                 {  
  123.                     sb.append(elementData[i].toString() + ", ");  
  124.                 }  
  125.                 for (int i = 0 ; i < rear ; i++)  
  126.                 {  
  127.                     sb.append(elementData[i].toString() + ", ");  
  128.                 }  
  129.                 int len = sb.length();  
  130.                 return sb.delete(len - 2 , len).append("]").toString();  
  131.             }  
  132.         }  
  133.     }  
  134.     public static void main(String[] args)  
  135.     {  
  136.         LoopQueue<String> queue   
  137.             = new LoopQueue<String>("aaaa" , 3);  
  138.         //添加两个元素  
  139.         queue.add("bbbb");  
  140.         queue.add("cccc");  
  141.         //此时队列已满  
  142.         System.out.println(queue);  
  143.         //删除一个元素后,队列可以再多加一个元素  
  144.         queue.remove();  
  145.         System.out.println("删除一个元素后的队列:" + queue);  
  146.         //再次添加一个元素,此时队列又满  
  147.         queue.add("dddd");  
  148.         System.out.println(queue);  
  149.         System.out.println("队列满时的长度:" + queue.length());  
  150.         //删除一个元素后,队列可以再多加一个元素  
  151.         queue.remove();  
  152.         //再次加入一个元素,此时队列又满  
  153.         queue.add("eeee");  
  154.         System.out.println(queue);  
  155.     }  
  156. }  

 链式队列的实现

 

Java代码  收藏代码
  1. public class LinkQueue<T>  
  2. {  
  3.     //定义一个内部类Node,Node实例代表链队列的节点。  
  4.     private class Node  
  5.     {  
  6.         //保存节点的数据  
  7.         private T data;  
  8.         //指向下个节点的引用  
  9.         private Node next;  
  10.         //无参数的构造器  
  11.         public Node()  
  12.         {  
  13.         }  
  14.         //初始化全部属性的构造器  
  15.         public Node(T data ,  Node next)  
  16.         {  
  17.             this.data = data;  
  18.             this.next = next;  
  19.         }  
  20.     }  
  21.     //保存该链队列的头节点  
  22.     private Node front;  
  23.     //保存该链队列的尾节点  
  24.     private Node rear;  
  25.     //保存该链队列中已包含的节点数  
  26.     private int size;  
  27.     //创建空链队列  
  28.     public LinkQueue()  
  29.     {  
  30.         //空链队列,front和rear都是null  
  31.         front = null;  
  32.         rear = null;  
  33.     }  
  34.     //以指定数据元素来创建链队列,该链队列只有一个元素  
  35.     public LinkQueue(T element)  
  36.     {  
  37.         front = new Node(element , null);  
  38.         //只有一个节点,front、rear都指向该节点  
  39.         rear = front;  
  40.         size++;  
  41.     }  
  42.     //返回链队列的长度    
  43.     public int length()  
  44.     {  
  45.         return size;  
  46.     }  
  47.     //将新元素加入队列  
  48.     public void add(T element)  
  49.     {  
  50.         //如果该链队列还是空链队列  
  51.         if (front == null)  
  52.         {  
  53.             front = new Node(element , null);  
  54.             //只有一个节点,front、rear都指向该节点  
  55.             rear = front;  
  56.         }  
  57.         else  
  58.         {  
  59.             //创建新节点  
  60.             Node newNode = new Node(element , null);  
  61.             //让尾节点的next指向新增的节点  
  62.             rear.next = newNode;  
  63.             //以新节点作为新的尾节点  
  64.             rear = newNode;  
  65.         }  
  66.         size++;  
  67.     }  
  68.     //删除队列front端的元素  
  69.     public T remove()  
  70.     {  
  71.         Node oldFront = front;  
  72.         front = front.next;  
  73.         oldFront.next = null;  
  74.         size--;  
  75.         return oldFront.data;  
  76.     }  
  77.     //访问链式队列中最后一个元素  
  78.     public T element()  
  79.     {  
  80.         return rear.data;  
  81.     }  
  82.     //判断链式队列是否为空队列  
  83.     public boolean empty()  
  84.     {  
  85.         return size == 0;  
  86.     }  
  87.     //清空链队列  
  88.     public void clear()  
  89.     {  
  90.         //将front、rear两个节点赋为null  
  91.         front = null;  
  92.         rear = null;  
  93.         size = 0;  
  94.     }  
  95.     public String toString()  
  96.     {  
  97.         //链队列为空链队列时  
  98.         if (empty())  
  99.         {  
  100.             return "[]";  
  101.         }  
  102.         else  
  103.         {  
  104.             StringBuilder sb = new StringBuilder("[");  
  105.             for (Node current = front ; current != null  
  106.                 ; current = current.next )  
  107.             {  
  108.                 sb.append(current.data.toString() + ", ");  
  109.             }  
  110.             int len = sb.length();  
  111.             return sb.delete(len - 2 , len).append("]").toString();  
  112.         }  
  113.     }  
  114.       
  115.     public static void main(String[] args)   
  116.     {  
  117.         LinkQueue<String> queue   
  118.             = new LinkQueue<String>("aaaa");  
  119.         //添加两个元素  
  120.         queue.add("bbbb");  
  121.         queue.add("cccc");  
  122.         System.out.println(queue);  
  123.         //删除一个元素后  
  124.         queue.remove();  
  125.         System.out.println("删除一个元素后的队列:" + queue);  
  126.         //再次添加一个元素  
  127.         queue.add("dddd");  
  128.         System.out.println("再次添加元素后的队列:" + queue);  
  129.         //删除一个元素后,队列可以再多加一个元素  
  130.         queue.remove();  
  131.         //再次加入一个元素  
  132.         queue.add("eeee");  
  133.         System.out.println(queue);  
  134.     }  
  135. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值