insert method for Priority Queue using Linked Lists

前端 未结 1 970
耶瑟儿~
耶瑟儿~ 2021-01-26 06:37

Firstly I feel I should mention this is for an assignment. I\'m not looking for a direct code answer just to point me in the right direction. We have been asked to implement a P

相关标签:
1条回答
  • 2021-01-26 07:04

    Here is some pseudocode code. (I have tested it by creating a queue)

    public void insert(int priority, int data) {
        Item item = new Item(priority, data);
    
        if (head == null) {
            head = item;
            item.setNext(null);
        } else {
            Item next = head;
            Item prev = next;
    
            do {
                if (priority > next.getPriority()) {
                    // break and insert
                    break;
                }
                prev = next;
                next = next.getNext();
            } while (next != null);
    
            item.setNext(next);
            if (item.getPriority() > head.getPriority()) {
                head = item;
            } else prev.setNext(item);
        }
    }
    

    You had the following problems in your insert method:

    prev = head;
    head.setNext(head);
    prev = pqItem;
    

    What does this piece of code even do? Here is what it does:

    You also did not consider the case in which you have more than two items in the queue. Imagine you have 5 items in the queue. And now you want to insert pqItem in the queue. pqItem has the least priority so it will get inserted at the end of the queue, right? Therefore, you need to traverse the queue (list) in order to get to the last item.

    0 讨论(0)
提交回复
热议问题