java linkedlist solution easy to understand


  • 0
    W
    public class PhoneDirectory {
        class ListNode {
            int val;
            ListNode next;
            public ListNode(int v) {
                val = v;
                next = null;
            }
        }
        Map<Integer, ListNode> occupy = new HashMap<>();
        int maxNum = 0;
        ListNode dummy = new ListNode(1);
        ListNode tail = new ListNode(1);
        /** Initialize your data structure here
         * 
            @param maxNumbers - The maximum numbers that can be stored in the phone directory. */
        public PhoneDirectory(int maxNumbers) {
            ListNode head = new ListNode(0);
            dummy.next = head;
            tail = head;
            for (int i = 1; i < maxNumbers; i++) {
                head.next = new ListNode(i);
                head = head.next;
                tail = head;
            }
        }
        
        /** Provide a number which is not assigned to anyone.
            @return - Return an available number. Return -1 if none is available. */
        public int get() {
            ListNode head = dummy.next;
            if (head == null) {
                return -1;
            }
            dummy.next = head.next;
            if (head.val == tail.val) {
                tail = dummy;
            }
            occupy.put(head.val, head);
            return head.val;
        }
        
        /** Check if a number is available or not. */
        public boolean check(int number) {
            return !occupy.containsKey(number);
        }
        
        /** Recycle or release a number. */
        public void release(int number) {
            if (!occupy.containsKey(number)) {
                return;
            }
            tail.next = new ListNode(number);
            tail = tail.next;
            
            occupy.remove(number);
        }
    }

  • 0
    B

    You don't need to create a new ListNode in the release() method. Just get the one stored in the map. In this way, you need to set head.next = null before add it into the map.


  • 0
    W

    @beefnoodle Yeah since java gc I think this is way can help my make less bug ;)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.