Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ring_queue;
- import java.util.HashSet;
- import java.util.Set;
- public class RingQueue<T> {
- private Node<T> head;
- private Node<T> tail;
- private int size;
- public void enqueue(T val, int id) {
- Node<T> node = new Node<T>(val, id);
- if(head == null) {
- head = node;
- } else {
- tail.next = node;
- }
- tail = node;
- tail.next = head;
- size++;
- }
- public int remove(Node<T> node) {
- int id = node.id;
- if(head == null) throw new IllegalStateException("head is null");
- if(head.id == id) {
- int toRemoveVal = (int) head.val;
- head = head.next;
- size--;
- return toRemoveVal;
- } else {
- Node<T> curr = head;
- while(true) {
- if(curr.next.id == id) {
- int toRemoveVal = (int) curr.next.val;
- curr.next = curr.next.next;
- size--;
- return toRemoveVal;
- }
- curr = curr.next;
- }
- }
- }
- public int size() {
- return size;
- }
- Set<Integer> seen = new HashSet<>();
- public void removeEvery(int k) {
- int position = 1;
- Node<T> curr = head;
- while(size > k) {
- if(position % k == 0) {
- if(!seen.contains(curr.id)) {
- remove(curr);
- System.out.println(this);
- }
- }
- position++;
- curr = curr.next;
- }
- }
- @Override
- public String toString() {
- StringBuilder result = new StringBuilder();
- int index = 0;
- Node<T> curr = head;
- while(true) {
- result.append(curr.val);
- if(index >= size) break; else result.append("->");
- index++;
- curr = curr.next;
- }
- return result.toString();
- }
- static class Node<T> {
- Node<T> next;
- final T val;
- final int id;
- public Node(T val, int id) {
- this.val = val;
- this.id = id;
- }
- public Node(T val, int id, Node<T> next) {
- this.next = next;
- this.val = val;
- this.id = id;
- }
- @Override
- public String toString() {
- return "Node{" +
- "next=" + next +
- ", id=" + id +
- ", val=" + val +
- '}';
- }
- }
- }
- package ring_queue;
- public class Client {
- public static void main(String[] args) {
- RingQueue<Integer> queue = new RingQueue<>();
- for (int i = 0; i < 20; i++) {
- queue.enqueue(i, i);
- }
- System.out.println(queue);
- queue.removeEvery(5);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement