/** * doA : implement the operation for A Pre-condition : x and y must exist the in the ListNode * Post-condition : if x is to the right of y, move to left of y */ public void doA(int x, int y) { ListNode lnY = null; ListNode lnX = null; // traverse the node until it reaches x, if it hits y along the way, continue for (ListNode n = head; n != null; n = n.getNext()) { if (n.getElement() == y) { lnY = n; } if (n.getElement() == x) { lnX = n; // settle the chains for x if (lnX == head && lnX == tail) { // only one node in the list head = null; tail = null; } } if (lnX != null && lnY != null) { // check whether x is on the left of Y if (lnY.getPrev() == lnX) break; // fix prev pointer if (lnX != tail) { lnX.getNext().setPrev(lnX.getPrev()); } else { tail = lnX.getPrev(); tail.setNext(null); } // fix next pointer if (lnX != head) { lnX.getPrev().setNext(lnX.getNext()); } else { head = lnX.getNext(); head.setPrev(null); } // insert it before y if (lnY != head) { lnX.setPrev(lnY.getPrev()); lnY.getPrev().setNext(lnX); } else { head = lnX; head.setPrev(null); } lnY.setPrev(lnX); lnX.setNext(lnY); } } }
/** * doR : implement the operation for R Pre-condition : valid x and there must be a ball labelled x * in the list Post-condition : remove the ball labelled x */ public void doR(int x) { for (ListNode n = head; n != null; n = n.getNext()) { if (n.getElement() == x) { // when found, remove that node if (n == head && n == tail) { // only one node in the list head = null; tail = null; } // fix prev pointer if (n != tail) { n.getNext().setPrev(n.getPrev()); } else { tail = n.getPrev(); tail.setNext(null); } // fix next pointer if (n != head) { n.getPrev().setNext(n.getNext()); } else { head = n.getNext(); head.setPrev(null); } } num_nodes--; } }