Esempio n. 1
0
  /**
   * 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--;
    }
  }
Esempio n. 2
0
  /**
   * Removes <strong>ListNode</strong> in <strong>List</strong>
   *
   * @param node
   */
  public void remove(ListNode node) {
    if (head.equals(node))
      head = head.getNext(); // previous head is now unreachable -- collected by jvm
    else {
      node.getPrev().setNext(node.getNext());
      if (node.getNext() != null) node.getNext().setPrev(node.getPrev());
    }

    size--;
  }
Esempio n. 3
0
  /**
   * doB : implement the operation for B Pre-condition : x and y must exist the in the ListNode
   * Post-condition : if x is to the left of y, move to right of y
   */
  public void doB(int x, int y) {
    ListNode lnX = null;
    ListNode lnY = null;

    // traverse the node until it reaches x, if it hits y along the way, break
    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 right of Y
        if (lnY.getNext() == 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 != tail) {
          lnX.setNext(lnY.getNext());
          lnY.getNext().setPrev(lnX);
        } else {
          tail = lnX;
          tail.setNext(null);
        }

        lnY.setNext(lnX);
        lnX.setPrev(lnY);
      }
    }
  }