Question
This programme is done by an chegg expert.. Can anyone can explain the whole code and how it's work? Please answer as soon as possible...
This programme is done by an chegg expert..
Can anyone can explain the whole code and how it's work? Please answer as soon as possible...
/***Save these Three files compile them with javac and run PriorityQueueTest.java file***/ /**************************** Node.java ****************************/
public class Node { public int data; public Node next;
public Node(int data) { this.data = data; } }
/**************************** SortedLinkedList.java ****************************/
public class SortedLinkedList { public Node head; public void offer(int data) { Node node = new Node(data); if(head==null){ head=node; return; } insert(node); } public int poll(){ if(head==null) throw new RuntimeException("Priority Queue Empty"); int data =head.data; head=head.next; return data; } public String toString() { StringBuffer sb = new StringBuffer(); Node itr = head; while (itr != null) { sb.append(itr.data + " "); itr = itr.next; } return sb.toString(); }
private void insert(Node newNode){ if(head.data>newNode.data){ newNode.next=head; head=newNode; return; } Node iterator=head.next; Node previous=head; while((iterator!=null) && (iterator.data<=newNode.data)){ previous=iterator; iterator=iterator.next; } newNode.next=iterator; previous.next=newNode; } }
/**************************** PriorityQueueTest.java ****************************/ public class PriorityQueueTest { public static void main(String[] args){ SortedLinkedList queue=new SortedLinkedList(); queue.offer(12); queue.offer(10); queue.offer(1); queue.offer(23); queue.offer(6); queue.offer(11); System.out.println(queue.poll()); System.out.println(queue.poll()); System.out.println(queue.poll()); System.out.println(queue.poll()); System.out.println(queue.poll()); System.out.println(queue.poll()); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started