class ListNode { private Object data; private ListNode next; ListNode(Object o) { data = o; next = null; } ListNode(Object o, ListNode nextNode) { data = o; next = nextNode; } void setData(Object data){ this.data = data; } void setNext(ListNode next){ this.next = next; } Object getData() { return data; } ListNode getNext() { return next; } } // class ListNode class EmptyListException extends RuntimeException { public EmptyListException () { super ("List is empty"); } } // class EmptyListException class LinkedList { private ListNode head; private ListNode tail; public LinkedList() { head = tail = null; } public boolean isEmpty() { return head == null; } public void addToHead(Object item) { if (isEmpty()) head = tail = new ListNode(item); else head = new ListNode(item,head); } public void addToTail(Object item) { if (isEmpty()) head = tail = new ListNode(item); else{ tail.setNext(new ListNode(item)); tail = tail.getNext(); } } public Object removeFromHead() throws EmptyListException { Object item = null; if (isEmpty()) throw new EmptyListException(); item = head.getData(); if ( head == tail ) head = tail = null; else head = head.getNext(); return item; } public Object removeFromTail() throws EmptyListException { Object item = null; if (isEmpty()) throw new EmptyListException(); item = tail.getData(); if (head == tail) head = tail = null; else{ ListNode current = head; while(current.getNext() != tail){ current = current.getNext(); } tail = current; current.setNext(null); } return item; } @Override public String toString () { String s = "[ "; ListNode current = head; while (current != null) { s += current.getData() + " "; current = current.getNext(); } return s + "]"; } public int count(){ if (isEmpty()) return 0; int count = 0; ListNode current = head; while (current != null){ count++; current = current.getNext(); } return count; } public Object get(int n){ ListNode current = head; if (n >= 1 && n <= count()){ for (int i = 1; i < n; i++){ current = current.getNext(); } return current.getData(); } else{ return null; } } public Object remove(int n){ if (n < 1 || n > count()) return null; ListNode current = head; ListNode previous = head; while (!current.getData().equals(get(n))){ current = current.getNext(); } if ( n == 1){ removeFromHead(); } else if (n == count()){ removeFromTail(); } else{ while (!previous.getData().equals(get(n-1))){ previous = previous.getNext(); } previous.setNext(current.getNext()); } return current.getData(); } public void add(int n, Object item){ ListNode current = head; ListNode previous = head; if (n <= 1){ addToHead(item); } else if (n > count()){ addToTail(item); } else{ while (!current.getData().equals(get(n))){ current = current.getNext(); } while (!previous.getData().equals(get(n-1))){ previous = previous.getNext(); } previous.setNext(new ListNode(item, current)); } } } // class LinkedList
Who can explain the logic of method?
Thank you