/* * Remove the nth element in the list. The first element is element 1. * Return the removed element to the caller. */ public E remove(int n) { LinkEntry<E> le = new LinkEntry<E>(); le = head; if (n == 1) { if (size() == 1) { head = tail = null; return le.element; } else { head = head.next; head.previous = null; return le.element; } } else if (n == size()) { le = tail; tail = tail.previous; tail.next = null; return le.element; } else { for (int i = 1; i < n; i++) le = le.next; le.previous.next = le.next; le.next.previous = le.previous; return le.element; } }
public void push(E e) { LinkEntry<E> temp = new LinkEntry<E>(); temp.element = e; temp.next = head; head = temp; num_elements++; System.out.println("Element is pushed to Stack List is: " + e); }
/* * Add e to the end of the doubly linked list. * Returns true - if e was successfully added, false otherwise. */ public boolean add(E e) { int length = size(); LinkEntry<E> le = new LinkEntry<E>(); le.element = e; if (head == null) head = tail = le; else { tail.next = le; le.previous = tail; tail = le; } if (size() - length == 1) return true; else return false; }
public boolean add_sorted(E e) { LinkEntry<E> ne = new LinkEntry<E>(); ne.element = e; if (head == null && tail == null) { head = tail = ne; } else { LinkEntry<E> prev = null; LinkEntry<E> temp; for (temp = head; temp != null; temp = temp.next) { int comp = ((Comparable) e).compareTo(temp.element); if (comp < 0) /* Element added is less than one on list. */ { break; } prev = temp; } if (prev == null) /* Adding as new head */ { ne.next = head; head = ne; } else if (temp == null) /* Adding as new tail */ { tail.next = ne; tail = ne; } else /* Adding in the middle */ { ne.next = prev.next; /* HAS TO BE IN THIS ORDER */ prev.next = ne; /* HAS TO BE IN THIS ORDER */ } } return true; }
// modified to make a circularly linked list public boolean add(E e) { LinkEntry<E> ne = new LinkEntry<E>(); ne.element = e; if (head == null && tail == null) { head = tail = ne; head.next = head; tail.next = head; } else { tail.next = ne; tail = ne; tail.next = head; } return true; }