常用算法和数据结构的操作

时间:2016-04-10 13:02:55

标签: data-structures

According to:

我认为这里的数据结构是一个队列,因为它从列表中删除了最旧的元素。你觉得怎么样?

1 个答案:

答案 0 :(得分:-1)

这正是队列数据结构(先进先出)。通知所有插入的项目都已添加到尾部,并且所有已删除的项目都会从 head 中删除。

序列的状态

List    : 1 12 5
Removed : -

- After First Remove ( * )
List    : 12 5
Removed : 1

- After Second Remove ( * * * )
List    : 7
Removed : 1 12 5 3

- After Third Remove ( * )
List    : 2 4 13
Removed : 1 12 5 3 7

- After Fourth Remove ( * * * )
List    : 14 15
Removed : 1 12 5 3 7 2 4 13

Java测试代码

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class QueueDemo {

    public static void main(String[] args) {
        Queue<Integer> queue = new LinkedList<>();
        List<Integer> removed = new LinkedList<>();

        queue.add(1);
        queue.add(12);
        queue.add(5);

        System.out.println("After First Insert");
        System.out.println("Queue: " + queue);
        System.out.println();

        removed.add(queue.poll());

        System.out.println("After First Remove ( * )");
        System.out.println("Queue   : " + queue);
        System.out.println("Removed : " + removed);
        System.out.println();

        queue.add(3);
        queue.add(7);

        removed.add(queue.poll());
        removed.add(queue.poll());
        removed.add(queue.poll());

        System.out.println("After Second Remove ( * * * ) ");
        System.out.println("Queue   : " + queue);
        System.out.println("Removed : " + removed);
        System.out.println();

        queue.add(2);
        queue.add(4);
        queue.add(13);

        removed.add(queue.poll());

        System.out.println("After Third Remove ( * ) ");
        System.out.println("Queue   : " + queue);
        System.out.println("Removed : " + removed);
        System.out.println();

        queue.add(14);
        queue.add(15);

        removed.add(queue.poll());
        removed.add(queue.poll());
        removed.add(queue.poll());

        System.out.println("After Fourth Remove ( * * * ) ");
        System.out.println("Queue   : " + queue);
        System.out.println("Removed : " + removed);
        System.out.println();
    }

}

测试代码的输出

After First Insert
Queue: [1, 12, 5]

After First Remove ( * )
Queue   : [12, 5]
Removed : [1]

After Second Remove ( * * * ) 
Queue   : [7]
Removed : [1, 12, 5, 3]

After Third Remove ( * ) 
Queue   : [2, 4, 13]
Removed : [1, 12, 5, 3, 7]

After Fourth Remove ( * * * ) 
Queue   : [14, 15]
Removed : [1, 12, 5, 3, 7, 2, 4, 13]