MartinGeorgiev

custom queue with add

Mar 28th, 2023
572
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.99 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Main {
  4.  
  5.     static class Node {
  6.         int data;
  7.         Node next;
  8.         Node prev;
  9.  
  10.         public Node(int data) {
  11.             this.data = data;
  12.         }
  13.     }
  14.  
  15.     static class CustomQueue {
  16.         Node head, tail;
  17.  
  18.         public CustomQueue() {
  19.             head = null;
  20.             tail = null;
  21.         }
  22.  
  23.         void enqueue(int x) {
  24.             Node newNode = new Node(x);
  25.  
  26.             if (tail == null) {
  27.                 head = tail = newNode;
  28.                 return;
  29.             }
  30.  
  31.             tail.next = newNode;
  32.             newNode.prev = tail;
  33.             tail = newNode;
  34.         }
  35.  
  36.         int dequeue() {
  37.             if (head == null) {
  38.                 return Integer.MIN_VALUE;
  39.             }
  40.  
  41.             Node temp = head;
  42.             head = head.next;
  43.  
  44.             if (head == null) {
  45.                 tail = null;
  46.             } else {
  47.                 head.prev = null;
  48.             }
  49.  
  50.             return temp.data;
  51.         }
  52.  
  53.         boolean isEmpty() {
  54.             return head == null;
  55.         }
  56.     }
  57.  
  58.     public static void main(String[] args) {
  59.         Scanner scanner = new Scanner(System.in);
  60.         int N = scanner.nextInt();
  61.         int searchElement = scanner.nextInt();
  62.         int position = findPosition(N, searchElement);
  63.         if (position == -1) {
  64.             System.out.println("Element not found");
  65.         } else {
  66.             System.out.println("Element found at position " + position);
  67.         }
  68.     }
  69.  
  70.     public static int findPosition(int N, int searchElement) {
  71.         CustomQueue queue = new CustomQueue();
  72.         queue.enqueue(N);
  73.         int index = 1;
  74.         while (!queue.isEmpty()) {
  75.             int element = queue.dequeue();
  76.             if (element == searchElement) {
  77.                 return index;
  78.             }
  79.             index++;
  80.             queue.enqueue(element + 1);
  81.             queue.enqueue(element * 2);
  82.         }
  83.         return -1;
  84.     }
  85. }
  86.  
Advertisement
Add Comment
Please, Sign In to add comment