Linked List example : List « Collections Data Structure « Java

Home
Java
1.2D Graphics GUI
2.3D
3.Advanced Graphics
4.Ant
5.Apache Common
6.Chart
7.Class
8.Collections Data Structure
9.Data Type
10.Database SQL JDBC
11.Design Pattern
12.Development Class
13.EJB3
14.Email
15.Event
16.File Input Output
17.Game
18.Generics
19.GWT
20.Hibernate
21.I18N
22.J2EE
23.J2ME
24.JavaFX
25.JDK 6
26.JDK 7
27.JNDI LDAP
28.JPA
29.JSP
30.JSTL
31.Language Basics
32.Network Protocol
33.PDF RTF
34.Reflection
35.Regular Expressions
36.Scripting
37.Security
38.Servlets
39.Spring
40.Swing Components
41.Swing JFC
42.SWT JFace Eclipse
43.Threads
44.Tiny Application
45.Velocity
46.Web Services SOA
47.XML
Java » Collections Data Structure » List 




Linked List example
       
/*
 * Copyright (c) 2000 David Flanagan.  All rights reserved.
 * This code is from the book Java Examples in a Nutshell, 2nd Edition.
 * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
 * You may study, use, and modify it for any non-commercial purpose.
 * You may distribute it non-commercially as long as you retain this notice.
 * For a commercial use license, or to purchase the book (recommended),
 * visit http://www.davidflanagan.com/javaexamples2.
 */

/**
 * This class implements a linked list that can contain any type of object that
 * implements the nested Linkable interface. Note that the methods are all
 * synchronized, so that it can safely be used by multiple threads at the same
 * time.
 */
public class LinkedList {
  /**
   * This interface defines the methods required by any object that can be
   * linked into a linked list.
   */
  public interface Linkable {
    public Linkable getNext()// Returns the next element in the list

    public void setNext(Linkable node)// Sets the next element in the list
  }

  // This class has a default constructor: public LinkedList() {}

  /** This is the only field of the class. It holds the head of the list */
  Linkable head;

  /** Return the first node in the list */
  public synchronized Linkable getHead() {
    return head;
  }

  /** Insert a node at the beginning of the list */
  public synchronized void insertAtHead(Linkable node) {
    node.setNext(head);
    head = node;
  }

  /** Insert a node at the end of the list */
  public synchronized void insertAtTail(Linkable node) {
    if (head == null)
      head = node;
    else {
      Linkable p, q;
      for (p = head; (q = p.getNext()) != null; p = q)
        /* no body */;
      p.setNext(node);
    }
  }

  /** Remove and return the node at the head of the list */
  public synchronized Linkable removeFromHead() {
    Linkable node = head;
    if (node != null) {
      head = node.getNext();
      node.setNext(null);
    }
    return node;
  }

  /** Remove and return the node at the end of the list */
  public synchronized Linkable removeFromTail() {
    if (head == null)
      return null;
    Linkable p = head, q = null, next = head.getNext();
    if (next == null) {
      head = null;
      return p;
    }
    while ((next = p.getNext()) != null) {
      q = p;
      p = next;
    }
    q.setNext(null);
    return p;
  }

  /**
   * Remove a node matching the specified node from the list. Use equals()
   * instead of == to test for a matched node.
   */
  public synchronized void remove(Linkable node) {
    if (head == null)
      return;
    if (node.equals(head)) {
      head = head.getNext();
      return;
    }
    Linkable p = head, q = null;
    while ((q = p.getNext()) != null) {
      if (node.equals(q)) {
        p.setNext(q.getNext());
        return;
      }
      p = q;
    }
  }

  /**
   * This is a test class that implements the Linkable interface
   */
  static class LinkableInteger implements Linkable {
    int i; // The data contained in the node

    Linkable next; // A reference to the next node in the list

    public LinkableInteger(int i) {
      this.i = i;
    // Constructor

    public Linkable getNext() {
      return next;
    // Part of Linkable

    public void setNext(Linkable node) {
      next = node;
    // Linkable

    public String toString() {
      return i + "";
    // For easy printing

    public boolean equals(Object o) { // For comparison
      if (this == o)
        return true;
      if (!(instanceof LinkableInteger))
        return false;
      if (((LinkableIntegero).i == this.i)
        return true;
      return false;
    }
  }

  /**
   * The test program. Insert some nodes, remove some nodes, then print
   * out all elements in the list. It should print out the numbers 4, 6,
   * 3, 1, and 5
   */
  public static void main(String[] args) {
    LinkedList ll = new LinkedList()// Create a list
    ll.insertAtHead(new LinkableInteger(1))// Insert some stuff
    ll.insertAtHead(new LinkableInteger(2));
    ll.insertAtHead(new LinkableInteger(3));
    ll.insertAtHead(new LinkableInteger(4));
    ll.insertAtTail(new LinkableInteger(5));
    ll.insertAtTail(new LinkableInteger(6));
    System.out.println(ll.removeFromHead())// Remove and print a node
    System.out.println(ll.removeFromTail())// Remove and print again
    ll.remove(new LinkableInteger(2))// Remove another one

    // Now print out the contents of the list.
    for (Linkable l = ll.getHead(); l != null; l = l.getNext())
      System.out.println(l);
  }

}
           
         
    
    
    
    
    
    
  














Related examples in the same category
1.Using the Double Brace Initialization.
2.Add to end Performance compare: LinkList and ArrayListAdd to end Performance compare: LinkList and ArrayList
3.Add to start Performance compare: LinkList and ArrayList
4.Convert array to list and sortConvert array to list and sort
5.Shuffle a listShuffle a list
6.Sort a listSort a list
7.Bidirectional Traversal with ListIteratorBidirectional Traversal with ListIterator
8.Int listInt list
9.List to array
10.List Reverse Test
11.Build your own Linked List class
12.List Search Test List Search Test
13.Convert a List to a Set
14.Set Operating on Lists: addAll, removeAll, retainAll, subList
15.Convert collection into array
16.Convert LinkedList to array
17.Convert Set into List
18.If a List contains an item
19.ListSet extends List and Set
20.List containing other lists
21.Helper method for creating list
22.Generic to list
23.List implementation with lazy array construction and modification tracking.
24.Utility methods for operating on memory-efficient lists. All lists of size 0 or 1 are assumed to be immutable.
25.A class that wraps an array with a List interface.
26.Splits the list.
27.Slice a list
28.A List that, like a Set, contains no duplicate Elements.
29.Determines if the given lists contain the same elements. We suppose that all the elements of the given lists are different.
30.List that allows items to be added with a priority that will affect the order in which they are later iterated over.
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.