用Java模拟一个堆栈或者队列数据结构。
首先得明白堆栈和队列的数据结构:
堆栈:先进后出
队列:先进先出
LinkedList中刚好有addFirst()和addLast()方法。
[java] view
plaincopyprint?
- public class Stack
{ - public static void main(String[] args) {
- StackTools tools = new StackTools();
- tools.add("a");
- tools.add("b");
- tools.add("c");
- tools.add("d");
- tools.remove();
- }
- }
- private
class StackTools { - private LinkedList<String> linkedList;
- public StackTools(){
- linkedList = new LinkedList<String>();
- }
- public void add(String string){
- linkedList.addFirst(string);
- }
- public void remove(){
- for(int i
= 0; i < linkedList.size(); i++){ - String content = linkedList.get(i);
- System.out.println(content);
- }
- }
- }
打印结果:
[java] view
plaincopyprint?
- d
- c
- b
- a
这是先进后出,这就是堆栈的数据结构,队列就简单了,只要把addFirst()方法改成addLast()方法就行。
代码如下:
[java] view
plaincopyprint?
- public class Queue
{ - public static void main(String[] args) {
- QueueTools tools = new QueueTools();
- tools.add("a");
- tools.add("b");
- tools.add("c");
- tools.add("d");
- tools.remove();
- }
- }
- private
class QueueTools { - private LinkedList<String>
linkedList; - public QueueTools(){
- linkedList = new LinkedList<String>();
- }
- public void add(String string){
- linkedList.addLast(string);
- }
- public void remove(){
- for(int i
= 0; i < linkedList.size(); i++){ - String content = linkedList.get(i);
- System.out.println(content);
- }
- }
- }
时间: 2024-10-12 11:12:05