Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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.
add(Object o): Appends the specified element to the end of this list. It returns a boolean value.
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.
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());
}
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());
}
}
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.
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.
import java.util.Scanner;
////////////////////////////////////////////////////////////////////////// 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.
This makes only minor changes so that elements are linked in both forward and backward directions.
package linkedlistexamples;
import java.util.Scanner;
////////////////////////////////////////////////////////////////////////// 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.
}
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.
package linkedlistexamples;
import java.util.*;
/////////////////////////////////////////////////////////////////////////////////////
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.
// 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
[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.