This implementation of LinkedList that is optimized for element removal. : Link List « Collections Data Structure « Java






This implementation of LinkedList that is optimized for element removal.

        
/***
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *    
 *    Linking this library statically or dynamically with other modules 
 *    is making a combined work based on this library. Thus, the terms and
 *    conditions of the GNU General Public License cover the whole
 *    combination.
 *    
 *    As a special exception, the copyright holders of this library give 
 *    you permission to link this library with independent modules to 
 *    produce an executable, regardless of the license terms of these 
 *    independent modules, and to copy and distribute the resulting 
 *    executable under terms of your choice, provided that you also meet, 
 *    for each linked independent module, the terms and conditions of the 
 *    license of that module.  An independent module is a module which 
 *    is not derived from or based on this library.  If you modify this 
 *    library, you may extend this exception to your version of the 
 *    library, but you are not obligated to do so.  If you do not wish 
 *    to do so, delete this exception statement from your version.
 *
 *    Project: www.simpledbm.org
 *    Author : Dibyendu Majumdar
 *    Email  : d dot majumdar at gmail dot com ignore
 */
//package org.simpledbm.common.util;

import java.util.Iterator;

/**
 * This implementation of LinkedList that is optimized for element removal. The
 * standard Java linked list implementation is non-intrusive and inefficient for
 * element removals. This implementation requires elements to extend the
 * {@link Linkable} abstract class.
 * <p>
 * The implementation is not thread-safe. Caller must ensure thread safety.
 * 
 * @author Dibyendu Majumdar
 */
public class SimpleLinkedList<E extends Linkable> implements Iterable<E> {

    Linkable head;

    Linkable tail;

    /**
     * Tracks the number of members in the list.
     */
    int count;

    private void setOwner(E link) {
        assert !link.isMemberOf(this);
        link.setOwner(this);
    }

    private void removeOwner(Linkable link) {
        assert link.isMemberOf(this);
        link.setOwner(null);
    }

    public final void addLast(E link) {
        setOwner(link);
        if (head == null)
            head = link;
        link.setPrev(tail);
        if (tail != null)
            tail.setNext(link);
        tail = link;
        link.setNext(null);
        count++;
    }

    public final void addFirst(E link) {
        setOwner(link);
        if (tail == null)
            tail = link;
        link.setNext(head);
        if (head != null)
            head.setPrev(link);
        head = link;
        link.setPrev(null);
        count++;
    }

    public final void insertBefore(E anchor, E link) {
        setOwner(link);
        if (anchor == null) {
            addFirst(link);
        } else {
            Linkable prev = anchor.getPrev();
            link.setNext(anchor);
            link.setPrev(prev);
            anchor.setPrev(link);
            if (prev == null) {
                head = link;
            } else {
                prev.setNext(link);
            }
            count++;
        }
    }

    public final void insertAfter(E anchor, E link) {
        setOwner(link);
        if (anchor == null) {
            addLast(link);
        } else {
            Linkable next = anchor.getNext();
            link.setPrev(anchor);
            link.setNext(next);
            anchor.setNext(link);
            if (next == null) {
                tail = link;
            } else {
                next.setPrev(link);
            }
            count++;
        }
    }

    private void removeInternal(Linkable link) {
        removeOwner(link);
        Linkable next = link.getNext();
        Linkable prev = link.getPrev();
        if (next != null) {
            next.setPrev(prev);
        } else {
            tail = prev;
        }
        if (prev != null) {
            prev.setNext(next);
        } else {
            head = next;
        }
        link.setNext(null);
        link.setPrev(null);
        count--;
    }

    public final void remove(E e) {
        removeInternal(e);
    }

    public final boolean contains(E link) {
        Linkable cursor = head;

        while (cursor != null) {
            if (cursor == link || cursor.equals(link)) {
                return true;
            } else {
                cursor = cursor.getNext();
            }
        }
        return false;
    }

    public final void clear() {
        count = 0;
        head = null;
        tail = null;
    }

    @SuppressWarnings("unchecked")
    public final E getFirst() {
        return (E) head;
    }

    @SuppressWarnings("unchecked")
    public final E getLast() {
        return (E) tail;
    }

    @SuppressWarnings("unchecked")
    public final E getNext(E cursor) {
        return (E) cursor.getNext();
    }

    public final int size() {
        return count;
    }

    public final boolean isEmpty() {
        return count == 0;
    }

    public final void push(E link) {
        addLast(link);
    }

    @SuppressWarnings("unchecked")
    public final E pop() {
        Linkable popped = tail;
        if (popped != null) {
            removeInternal(popped);
        }
        return (E) popped;
    }

    public Iterator<E> iterator() {
        return new Iter<E>(this);
    }

    static final class Iter<E extends Linkable> implements Iterator<E> {

        final SimpleLinkedList<E> ll;

        E nextE;

        E currentE;

        Iter(SimpleLinkedList<E> ll) {
            this.ll = ll;
            nextE = ll.getFirst();
        }

        public boolean hasNext() {
            return nextE != null;
        }

        @SuppressWarnings("unchecked")
        public E next() {
            currentE = nextE;
            if (nextE != null) {
                nextE = (E) nextE.getNext();
            }
            return currentE;
        }

        public void remove() {
            if (currentE != null) {
                ll.remove(currentE);
                currentE = null;
            }
        }
    }
}

/**
 * Objects that need to be managed through the SimpleLinkedList must extend this
 * class.
 * 
 * @author Dibyendu Majumdar
 * @since 06 Jan 2007
 */
 abstract class Linkable {

    Linkable next;

    Linkable prev;

    /**
     * Notes that the element is a member of a list.
     */
    Object owner;

    Linkable getNext() {
        return next;
    }

    void setNext(Linkable link) {
        next = link;
    }

    Linkable getPrev() {
        return prev;
    }

    void setPrev(Linkable link) {
        prev = link;
    }

    public final boolean isMemberOf(SimpleLinkedList<? extends Linkable> list) {
        return this.owner == list;
    }

    final void setOwner(SimpleLinkedList<? extends Linkable> list) {
        this.owner = list;
    }
}

   
    
    
    
    
    
    
    
  








Related examples in the same category

1.Use for each loop to go through elements in a linkedlist
2.Use addFirst method to add value to the first position in a linked list
3.To insert an object into a specific position into the list, specify the index in the add method
4.Updating LinkedList Items
5.Convert LinkedList to Array with zero length array
6.Convert LinkedList to Array with full length array
7.Checking what item is first in line without removing it: element
8.Removing the first item from the queue: poll
9.Convert a LinkedList to ArrayList
10.Add elements at beginning and end of LinkedList Java example
11.Check if a particular element exists in LinkedList Java example
12.Create an object array from elements of LinkedList Java example
13.Get elements from LinkedList Java example
14.Get first and last elements from LinkedList Java example
15.Get SubList from LinkedList Java example
16.Iterate through elements of Java LinkedList using Iterator example
17.Remove all elements or clear LinkedList Java example
18.Iterate through elements of Java LinkedList using ListIterator example
19.Remove first and last elements of LinkedList Java example
20.Remove range of elements from LinkedList Java example
21.Remove specified element from LinkedList Java example
22.Replace an Element of LinkedList Java example
23.Search elements of LinkedList Java example
24.Add or insert an element to ArrayList using Java ListIterator Example
25.Finding an Element in a Sorted List
26.Create a list with an ordered list of strings
27.Search for a non-existent element
28.Use an Iterator to cycle through a collection in the forward direction.
29.Implementing a Queue with LinkedList
30.Implementing a Stack
31.Using a LinkedList in multi-thread
32.Convert Collection to ArrayList
33.Wrap queue to synchronize the methods
34.Making a stack from a LinkedListMaking a stack from a LinkedList
35.Single linked list
36.Double LinkedList
37.Doubly Linked listDoubly Linked list
38.A class for you to extend when you want object to maintain a doubly linked list
39.A simple Doubly Linked list class, designed to avoid O(n) behaviour on insert and delete.A simple Doubly Linked list class, designed to avoid O(n) behaviour on insert and delete.
40.A List helper class that attempts to avoid unneccessary List creation.
41.This program demonstrates operations on linked lists
42.Simple linked list class which uses a Comparator to sort the nodes.