Search code examples
javalinked-listpriority-queue

Removing min from LinkedList


I want to remove 3 from this list but I am not sure where to start. I am storing a sequence of numbers in a Priority Queue that implements a linked list and trying to locate the min and remove it from the priority queue using the removeMin method

import java.util.Iterator;
import java.util.LinkedList;
public class Test {

    static LinkedList<Integer> list = new LinkedList<Integer>();

    public static void main(String[] args) {

        list.add(10);
        list.add(4);
        list.add(12);
        list.add(3);
        list.add(7);
        System.out.println(removeMin());
    }

    public static Integer removeMin() {
        LinkedList<Integer> pq = new LinkedList<Integer>();
        Iterator it = pq.iterator();

        for (int i = 0; i < list.size(); i++) {
            pq.add(list.remove());
        }

        int min = pq.get(0);

        while (it.hasNext()) {
            // help here
        }

        return pq.remove();
    }

Solution

  • Try this:

    Solution 1

    LinkedList<Integer> list = new LinkedList<Integer>();
            list.add(10);
            list.add(4);
            list.add(12);
            list.add(3);
            list.add(7);
            Collections.sort(list);
            list.removeFirst();
            list.forEach(System.out::println);
    

    Solution 2:

     LinkedList<Integer> list = new LinkedList<Integer>();
        list.add(10);
        list.add(4);
        list.add(12);
        list.add(3);
        list.add(7);
    
        int min=Integer.MAX_VALUE;
        int pos=0;
        int remPos=0;
        Iterator<Integer> iterator = list.iterator();
    
        while(iterator.hasNext()){
            Integer element = iterator.next();
            if(element<min){
                min=element;
                remPos=pos;
            }
            pos++;
        }
    
        list.remove(remPos);
        list.forEach(System.out::println);