Sei sulla pagina 1di 15

Link List Example in Java

                          

In this example, we are going to show the use of java.util.LinkedList class. You will be
creating an object of link list class and performing various operation like adding and removing
object.  

This class extends AbstractSequentialList and implements List, Cloneable, Serializable. It


permits all elements including null. LinkedList class provides  methods get, insert and
remove  an element at the beginning and end of the list.

In this example we are using six methods of LinkedList class.

add(Object o): Appends the specified element to the end of this list. It returns a boolean value.

size(): Returns the number of elements in this list.

addFirst(Object o): Inserts the given element at the beginning of this list.

addLast(Object o): Inserts the given element at the last of this list.

add(int index,Object o): Insert the specified element at the specified position in this list. It
throws IndexOutOfBoundsException if index is out of range. 

remove(int index): Remove the element at the specified position in this list. It returns the
element that was removed from the list. It throws IndexOutOfBoundsException if index is
out of range. 

The code of the program is given below:

import java.util.*;

public class LinkedListDemo{
  public static void main(String[] args){
    LinkedList link=new LinkedList();
    link.add("a");
    link.add("b");
    link.add(new Integer(10));
    System.out.println("The contents of array is" + link);
    System.out.println("The size of an linkedlist is" + link.size());
    
    link.addFirst(new Integer(20));
    System.out.println("The contents of array is" + link);
    System.out.println("The size of an linkedlist is" + link.size());

    link.addLast("c");
    System.out.println("The contents of array is" + link);
    System.out.println("The size of an linkedlist is" + link.size());

    link.add(2,"j");
    System.out.println("The contents of array is" + link);
    System.out.println("The size of an linkedlist is" + link.size());

    link.add(1,"t");
    System.out.println("The contents of array is" + link);
    System.out.println("The size of an linkedlist is" + link.size());

    link.remove(3);
    System.out.println("The contents of array is" + link);
    System.out.println("The size of an linkedlist is" + link.size());
  }

Link List Example in Java


                          
In this example, we are going to show the
use of java.util.LinkedList class. You will be
creating an object of link list class and
performing various operation like adding
and removing object.  
This class extends AbstractSequentialList
and implements List, Cloneable,
Serializable. It permits all elements
including null. LinkedList class provides 
methods get, insert and remove  an element
at the beginning and end of the list.
In this example we are using six methods of
LinkedList class.
add(Object o): Appends the specified
element to the end of this list. It returns a
boolean value.
size(): Returns the number of elements in
this list.
addFirst(Object o): Inserts the given
element at the beginning of this list.
addLast(Object o): Inserts the given element
at the last of this list.
add(int index,Object o): Insert the specified
element at the specified position in this list.
It throws IndexOutOfBoundsException if
index is out of range. 
remove(int index): Remove the element at
the specified position in this list. It returns
the element that was removed from the list.
It throws IndexOutOfBoundsException if
index is out of range. 
The code of the program is given below:
import java.util.*;

public class LinkedListDemo{
  public static void main(String[] args){
    LinkedList link=new LinkedList();
    link.add("a");
    link.add("b");
    link.add(new Integer(10));
    System.out.println("The contents of array is" + link);
    System.out.println("The size of an linkedlist is" + link.size());
    
    link.addFirst(new Integer(20));
    System.out.println("The contents of array is" + link);
    System.out.println("The size of an linkedlist is" + link.size());

    link.addLast("c");
    System.out.println("The contents of array is" + link);
    System.out.println("The size of an linkedlist is" + link.size());

    link.add(2,"j");
    System.out.println("The contents of array is" + link);
    System.out.println("The size of an linkedlist is" + link.size());

    link.add(1,"t");
    System.out.println("The contents of array is" + link);
    System.out.println("The size of an linkedlist is" + link.size());

    link.remove(3);
    System.out.println("The contents of array is" + link);
    System.out.println("The size of an linkedlist is" + link.size());
  }
}

Output of the program will be like this:


The contents of array is[a, b,
10]
The size of an linkedlist is3
The contents of array is[20, a,
b, 10]
The size of an linkedlist is4
The contents of array is[20, a,
b, 10, c]
The size of an linkedlist is5
The contents of array is[20, a,
j, b, 10, c]
The size of an linkedlist is6
The contents of array is[20, t,
a, j, b, 10, c]
The size of an linkedlist is7
The contents of array is[20, t,
a, b, 10, c]
The size of an linkedlist is6

This shows three programs.

 A simple singly-linked list. This shows the basics.

 A doubly-linked list. This is almost as simple as the singly-linked list, but makes some operations
easier.

 Use of the java.util.LinkedList class, which is easy to use because it hides the details.

Simple singly-linked list done "by hand"

The following program is an example of a very simple implementation of a singly-linked list. You should
become very comfortable with this. Altho you should always prefer the predefined
java.util.LinkedList class when working with linked lists, understanding linking objects is essential
to building other structures for which there is no predefined library class.

// Purpose: Demonstrates a really simple singly-linked list.


// Main builds list of words, prints it using two styles.
// Author : Fred Swartz, 21 Feb 2006, placed in the public domain.

import java.util.Scanner;

public class SimpleSinglyLinkedList {


public static void main(String[] args) {
Scanner in = new Scanner(System.in);

Elem front = null; // First element of list.


Elem back = null; // Last element of list.

//... Read a list of words.


while (in.hasNext()) {
String word = in.next();

Elem e = new Elem(); // Create a new list element.


e.data = word; // Set the data field.

//... Two cases must be handled differently


if (front == null) {
//... When the list is empty, we have to set the front pointer.
front = e; // Back element will be set below.
} else {
//... When we already have elements, we need to link to it.
back.next = e; // Link last elem to new element.
}
back = e; // Update back to link to new element.
}

//... While loop to print list in forward order.


System.out.println("*** Print words in order of entry");
Elem curr = front;
while (curr != null) {
System.out.println(curr.data);
curr = curr.next;
}

System.out.println("*** Print words in order of entry");


for (Elem e = front; e != null; e = e.next) {
System.out.println(e.data);
}

//... Printing list in backward order is an interesting exercise.


// But too much for here.
}
}

////////////////////////////////////////////////////////////////////////// Elem
// Simple class to hold data are sometimes defined with public fields.
// This practice isn't good, but was done here for simplicity.
class Elem {
public Elem next; // Link to next element in the list.
public String data; // Reference to the data.

}A simple doubly-linked list

This makes only minor changes so that elements are linked in both forward and backward directions.

// Purpose: Shows a simple doubly-linked list. Very few changes


// from singly-linked, but allows backwards traversal and
// easier insertion and deletion.
// Main builds list of words, prints it forward and backward.
// Author : Fred Swartz, 21 Feb 2006, placed in the public domain.

package linkedlistexamples;

import java.util.Scanner;

public class SimpleDoublyLinkedList {


public static void main(String[] args) {
Scanner in = new Scanner(System.in);

Elem2 front = null; // First element of list.


Elem2 back = null; // Last element of list.

//... Read a list of words.


while (in.hasNext()) {
String word = in.next();

Elem2 e = new Elem2(); // Create a new list element.


e.data = word; // Set the data field.

//... Two cases must be handled differently


if (front == null) {
//... When the list is empty, we have to set the front pointer.
front = e; // Back element will be set below.
} else {
//... When we already have elements, we need to link to it.
back.next = e; // Link last elem to new element.
}
e.prev = back;
back = e; // Update back to link to new element.
}

System.out.println("*** Print words in order of entry");


for (Elem2 e = front; e != null; e = e.next) {
System.out.println(e.data);
}

System.out.println("*** Print words in reverse order of entry");


for (Elem2 e = back; e != null; e = e.prev) {
System.out.println(e.data);
}
}
}

////////////////////////////////////////////////////////////////////////// Elem2
// Simple classes to hold data are sometimes defined with public fields.
// This practice isn't good, but was done here for simplicity.
class Elem2 {
public Elem2 next; // Link to next element in the list.
public Elem2 prev; // Link to the previous element.
public String data; // Reference to the data.
}

Same program using java.util.LinkedList class

This program does the same thing as above using java.util.LinkedList, which hides the linking infrastructure
and extra class. It is a doubly-linked list so moving in both directions is possible.

// Purpose: Contrast library LinkedList with the manual solutions.


// The link management infrastructure is completely hidden.
// Author : Fred Swartz, 21 Feb 2006, placed in the public domain.

package linkedlistexamples;

import java.util.*;

public class LibraryLinkedList {


public static void main(String[] args) {
Scanner in = new Scanner(System.in);

LinkedList<String> lst = new LinkedList<String>();

//... Read and build list of words.


while (in.hasNext()) {
String word = in.next();
lst.add(word);
}

//... Enhanced for loop to print list forward.


// Could also use an Iterator (forward only) or
// ListIterator (forward or backward).
System.out.println("*** Print words in order of entry");
for (String s : lst) {
System.out.println(s);
}

//... Use ListIterator go to backward. Start at end.


System.out.println("*** Print words in reverse order of entry");
for (ListIterator<String> lit = lst.listIterator(lst.size()); lit.hasPrevious();) {
System.out.println(lit.previous());
}
}
}

/////////////////////////////////////////////////////////////////////////////////////

In computer science, a linked list is one of the fundamental data structures used in computer programming. It consists of
a sequence of nodes, each containing arbitrary data fields and one or two references ("links") pointing to the next and/or
previous nodes. A linked list is a self-referential datatype because it contains a pointer or link to another data of the
same type. Linked lists permit insertion and removal of nodes at any point in the list in constant time, but do not allow
random access. Several different types of linked list exist: singly-linked lists, doubly-linked lists, and circularly-linked
lists.

Linked lists can be implemented in most languages. Languages such as Lisp and Scheme have the data structure built in,
along with operations to access the linked list. Procedural languages such as C, C++, and Java typically rely on mutable
references to create linked lists.

Following code shows how to implement a linked list in Java:

// LinkedList class
//
// CONSTRUCTION: with no initializer
// Access is via LinkedListIterator class
//
// ******************PUBLIC OPERATIONS*********************
// boolean isEmpty( )     --> Return true if empty; else false
// void makeEmpty( )      --> Remove all items
// LinkedListIterator zeroth( )
//                        --> Return position to prior to first
// LinkedListIterator first( )
//                        --> Return first position
// void insert( x, p )    --> Insert x after current iterator position p
// void remove( x )       --> Remove x
// LinkedListIterator find( x )
//                        --> Return position that views x
// LinkedListIterator findPrevious( x )
//                        --> Return position prior to x
// ******************ERRORS********************************
// No special errors
/**
 * Linked list implementation of the list
 *    using a header node.
 * Access to the list is via LinkedListIterator.
 * @author Mark Allen Weiss
 * @see LinkedListIterator
 */
public class LinkedList {
    /**
     * Construct the list
     */
    public LinkedList( ) {
        header = new ListNode( null );
    }
    
    /**
     * Test if the list is logically empty.
     * @return true if empty, false otherwise.
     */
    public boolean isEmpty( ) {
        return header.next == null;
    }
    
    /**
     * Make the list logically empty.
     */
    public void makeEmpty( ) {
        header.next = null;
    }
    
    /**
     * Return an iterator representing the header node.
     */
    public LinkedListIterator zeroth( ) {
        return new LinkedListIterator( header );
    }
    
    /**
     * Return an iterator representing the first node in the list.
     * This operation is valid for empty lists.
     */
    public LinkedListIterator first( ) {
        return new LinkedListIterator( header.next );
    }
    
    /**
     * Insert after p.
     * @param x the item to insert.
     * @param p the position prior to the newly inserted item.
     */
    public void insert( Object x, LinkedListIterator p ) {
        if( p != null && p.current != null )
            p.current.next = new ListNode( x, p.current.next );
    }
    
    /**
     * Return iterator corresponding to the first node containing an item.
     * @param x the item to search for.
     * @return an iterator; iterator is not valid if item is not found.
     */
    public LinkedListIterator find( Object x ) {
        ListNode itr = header.next;
        
        while( itr != null && !itr.element.equals( x ) )
            itr = itr.next;
        
        return new LinkedListIterator( itr );
    }
    
    /**
     * Return iterator prior to the first node containing an item.
     * @param x the item to search for.
     * @return appropriate iterator if the item is found. Otherwise, the
     * iterator corresponding to the last element in the list is returned.
     */
    public LinkedListIterator findPrevious( Object x ) {
        ListNode itr = header;
        
        while( itr.next != null && !itr.next.element.equals( x ) )
            itr = itr.next;
        
        return new LinkedListIterator( itr );
    }
    
    /**
     * Remove the first occurrence of an item.
     * @param x the item to remove.
     */
    public void remove( Object x ) {
        LinkedListIterator p = findPrevious( x );
        
        if( p.current.next != null )
            p.current.next = p.current.next.next;  // Bypass deleted node
    }
    
    // Simple print method
    public static void printList( LinkedList theList ) {
        if( theList.isEmpty( ) )
            System.out.print( "Empty list" );
        else {
            LinkedListIterator itr = theList.first( );
            for( ; itr.isValid( ); itr.advance( ) )
                System.out.print( itr.retrieve( ) + " " );
        }
        
        System.out.println( );
    }
    
    private ListNode header;
    
    // In this routine, LinkedList and LinkedListIterator are the
    // classes written in Section 17.2.
    public static int listSize( LinkedList theList ) {
        LinkedListIterator itr;
        int size = 0;
        
        for( itr = theList.first(); itr.isValid(); itr.advance() )
            size++;
        
        return size;
    }
    
    public static void main( String [ ] args ) {
        LinkedList         theList = new LinkedList( );
        LinkedListIterator theItr;
        int i;
        
        theItr = theList.zeroth( );
        printList( theList );
        
        for( i = 0; i < 10; i++ ) {
            theList.insert( new Integer( i ), theItr );
            printList( theList );
            theItr.advance( );
        }
        System.out.println( "Size was: " + listSize( theList ) );
        
        for( i = 0; i < 10; i += 2 )
            theList.remove( new Integer( i ) );
        
        for( i = 0; i < 10; i++ )
            if( ( i % 2 == 0 ) == ( theList.find( new Integer( i ) ).isValid( 
) ) )
                System.out.println( "Find fails!" );
        
        System.out.println( "Finished deletions" );
        printList( theList );
    }
    
}

// LinkedListIterator class; maintains "current position"
//
// CONSTRUCTION: Package visible only, with a ListNode
//
// ******************PUBLIC OPERATIONS*********************
// void advance( )        --> Advance
// boolean isValid( )     --> True if at valid position in list
// Object retrieve        --> Return item in current position

/**
 * Linked list implementation of the list iterator
 *    using a header node.
 * @author Mark Allen Weiss
 * @see LinkedList
 */
public class LinkedListIterator {
    /**
     * Construct the list iterator
     * @param theNode any node in the linked list.
     */
    LinkedListIterator( ListNode theNode ) {
        current = theNode;
    }
    
    /**
     * Test if the current position is a valid position in the list.
     * @return true if the current position is valid.
     */
    public boolean isValid( ) {
        return current != null;
    }
    
    /**
     * Return the item stored in the current position.
     * @return the stored item or null if the current position
     * is not in the list.
     */
    public Object retrieve( ) {
        return isValid( ) ? current.element : null;
    }
    
    /**
     * Advance the current position to the next node in the list.
     * If the current position is null, then do nothing.
     */
    public void advance( ) {
        if( isValid( ) )
            current = current.next;
    }
    
    ListNode current;    // Current position
}

// Basic node stored in a linked list
// Note that this class is not accessible outside
// of package weiss.nonstandard

class ListNode {
    // Constructors
    public ListNode( Object theElement ) {
        this( theElement, null );
    }
    
    public ListNode( Object theElement, ListNode n ) {
        element = theElement;
        next    = n;
    }
    
    public Object   element;
    public ListNode next;
}
//////////////////////////////////////////BEST///////////////////////////////////////////////

Often in programming we are required to systematically store some type of information. A prime example of this is to
use arrays but when you don’t know the amount of information to be stored we need a dynamic data structure.
One option for us is to use a linked list. A linked list works by creating a collection of objects (nodes) which both carry
the data we want to store and a reference to the next node in the list. So the first node in the list points to the next
node and then the next points to the one after that until we reach the last node which will point to null. This way all we
really need to keep track of is the first node, as knowing it will enable us to access any node down the list (because
they each point to each other, they are linked). And whenever you add a node it goes to the end of the list (as in the
current last node begins to point to the new node and the new node, of course, to null [and it is the new last node
now]). Let’s do an example:

Example

Let’s pretend we need to store a collection of integers and then display them all. If we knew the amount of
integers we were going to store the most obvious choice would be an array but we don’t so we need a dynamic
data structure. If we decide to use a linked list then the first thing to do is to write a class for the node that will hold our
integer. All the node really needs to have is two instance variables: one for the integer and one for the reference to
the next node in the list (as well as the accessor methods and the constructor).

class node
{ private int data; //holds an arbitrary integer
private node next; //reference to the next node

public node(int d, node n) //constructor


{ data = d;
next = n;
}
//these methods let us use our variables
public void setNext(node n)
{ next=n;}

public void setData(int d)


{ data=d;}

public node getNext()


{ return next;}

public int getData()


{ return data;}
}
Now that we have the basic node class that will make up the linked list it’s pretty easy to think up a display
algorithm if we define the first node (and last node) to be:

private static node firstNode; //a reference to the first node


private static node lastNode = null; //a reference to the last node

[Note: by this point we are now in the main class so firstNode and lastNode are class variables]. All you would need
to do is loop while the next node does not equal null. Such that:

public static void display() //displays all the data in the nodes
{ node n=firstNode;
while(n!=null) //loops forward displaying node’s data (the integers)
{ System.out.print(n.getData()+", ");
n=n.getNext(); //move to the next node in the list
}
}

Now we must create the actual linked list by writing a method that will not only construct the node but put it at the end
of the list (set the last node's next pointer to the new node). We already have a reference to the first and last node so
by using that information we can tell one of two conditions: that the node we are creating is the first node or it is not.
So:

public static void create(int d) //inserts the node into the list
{ node n=new node(d,null); //create node
if(lastNode != null) //if it is not the first node
{ lastNode.setNext(n);lastNode=n;}
else //if n is the first node
{ firstNode=n;lastNode=n;}
}

This is basically all you really need to know. All that’s left is just to write a little loop prompting the user for
numbers and then passing those numbers into create() and then to see if it works you can display() the nodes (or
rather the integers) but I’ll leave that up to you.

Conclusion

Linked lists are a great way to store a theoretically infinite amount of data (of course this isn’t really possible) with
a small and versatile amount of code. They are great in that you can change and write them to serve your particular
needs. For example: our lists were one directional, in that the individual node has no idea who is behind him in the
list. This can be easily altered by the addition of a reference to the node behind as well as in front. This will give you
greater control over the list. We could also write sorting algorithms, delete functions, and any number of methods that
we find beneficial.

Potrebbero piacerti anche