Lista Ligada Estrutura com nós que armazenam elementos manter referências para elementos do início e fim da lista Operações Inserir: a seguir à posição corrente Remover: na posição corrente Pesquisar: por conteúdo ou por posição first last Listas - 1 package weiss.nonstandard; Nó de Lista Ligada // Basic node stored in a linked list // Note that this class is not accessible outside // of package weiss.nonstandard class ListNode public ListNode( Object theelement ) this( theelement, null ); public ListNode( Object theelement, ListNode n ) element = theelement; next = n; public Object element; public ListNode next; Listas - 2 Listas-1
Nós: inserção e remoção Nó da lista Class ListNode Object element; ListNode next; Inserir a seguir ao nó corrente tmp = new ListNode(); tmp.element = x; tmp.next = current.next; current.next = tmp; ou current.next = new ListNode(x, current.next); Apagar a seguir ao nó corrente current.next = current.next.next; Listas - 3 Nós cabeçalho e iteradores Nós de cabeçalho Usados para evitar tratar como casos especiais a inserção e remoção no primeiro lugar da lista Garantem que cada nó da lista tem sempre um nó anterior Percorrer a lista Aplicação manipula referências para nós da lista não pode garantir-se que as referências são válidas Lista mantém a posição corrente e acesso é por métodos garante-se consistência das referências só uma visita à lista Iteradores permitem manter posição corrente independente da lista Listas - 4 Listas-2
Nó de lista duplamente ligada * This is the doubly-linked list node. private static class Node public Node( Object d, Node p, Node n ) data = d; prev = p; next = n; public Object data; public Node prev; public Node next; Listas - 5 package weiss.util; * LinkedList class implements a doubly-linked list. public class LinkedList extends AbstractCollection implements List private static final Node NOT_FOUND = null; private int thesize; private Node beginmarker; private Node endmarker; private int modcount = 0; Listas - 6 Listas-3
* Construct an empty LinkedList. public LinkedList( ) clear( ); * Construct a LinkedList with same items as another Collection. public LinkedList( Collection other ) clear( ); Iterator itr = other.iterator( ); while( itr.hasnext( ) ) add( itr.next( ) ); Listas - 7 * Returns the number of items in this collection. * @return the number of items in this collection. public int size( ) return thesize; * Tests if some item is in this collection. * @param x any object. * @return true if this collection contains an item equal to x. public boolean contains( Object x ) return findpos( x )!= NOT_FOUND; Listas - 8 Listas-4
* Returns the position of first item matching x in this collection, * or NOT_FOUND if not found. * @param x any object. * @return the position of first item matching x in this collection, * or NOT_FOUND if not found. private Node findpos( Object x ) for( Node p = beginmarker.next; p!= endmarker; p = p.next ) if( x == null ) if( p.data == null ) return p; else if( x.equals( p.data ) ) return p; return NOT_FOUND; Listas - 9 * Adds an item to this collection, at the end. public boolean add( Object x ) addlast( x ); return true; * Adds an item to this collection, at specified position. * Items at or after that position are slid one position higher. public void add( int idx, Object x ) Node p = getnode( idx ); Node newnode = new Node( x, p.prev, p ); newnode.prev.next = newnode; p.prev = newnode; thesize++; modcount++; Listas - 10 Listas-5
* Adds an item to this collection, at front. * Other items are slid one position higher. * @param x any object. public void addfirst( Object x ) add( 0, x ); * Adds an item to this collection, at end. * @param x any object. public void addlast( Object x ) add( size( ), x ); Listas - 11 * Returns the first item in the list. * @throws NoSuchElementException if the list is empty. public Object getfirst( ) if( isempty( ) ) throw new NoSuchElementException( ); return getnode( 0 ).data; * Returns the last item in the list. * @throws NoSuchElementException if the list is empty. public Object getlast( ) if( isempty( ) ) throw new NoSuchElementException( ); return getnode( size( ) - 1 ).data; Listas - 12 Listas-6
* Removes the first item in the list. * @return the item was removed from the collection. * @throws NoSuchElementException if the list is empty. public Object removefirst( ) if( isempty( ) ) throw new NoSuchElementException( ); return remove( getnode( 0 ) ); * Removes the last item in the list. * @return the item was removed from the collection. * @throws NoSuchElementException if the list is empty. public Object removelast( ) if( isempty( ) ) throw new NoSuchElementException( ); return remove( getnode( size( ) - 1 ) ); Listas - 13 * Removes an item from this collection. * @param x any object. * @return true if this item was removed from the collection. public boolean remove( Object x ) Node pos = findpos( x ); if( pos == NOT_FOUND ) return false; else remove( pos ); return true; * Returns the item at position idx. public Object get( int idx ) return getnode( idx ).data; Listas - 14 Listas-7
* Changes the item at position idx. * @param idx the index to change. * @param newval the new value. * @return the old value. * @throws IndexOutOfBoundsException if index is out of range. public Object set( int idx, Object newval ) Node p = getnode( idx ); Object oldval = p.data; p.data = newval; return oldval; Listas - 15 * Gets the Node at position idx, which must range from 0 to size( ). private Node getnode( int idx ) Node p; if( idx < 0 idx > size( ) ) throw new IndexOutOfBoundsException( "getnode index: " + idx + "; size: " + size( ) ); if( idx < size( ) / 2 ) p = beginmarker.next; for( int i = 0; i < idx; i++ ) p = p.next; else p = endmarker; for( int i = size( ); i > idx; i-- ) p = p.prev; return p; Listas - 16 Listas-8
* Removes an item from this collection. * @param idx the index of the object. * @return the item was removed from the collection. public Object remove( int idx ) return remove( getnode( idx ) ); * Removes the object contained in Node p. * @param p the Node containing the object. * @return the item was removed from the collection. private Object remove( Node p ) p.next.prev = p.prev; p.prev.next = p.next; thesize--; modcount++; return p.data; Listas - 17 * Change the size of this collection to zero. public void clear( ) beginmarker = new Node( "BEGINMARKER", null, null ); endmarker = new Node( "ENDMARKER", beginmarker, null ); beginmarker.next = endmarker; thesize = 0; modcount++; Listas - 18 Listas-9
* Obtains an Iterator object used to traverse the collection. * @return an iterator positioned prior to the first element. public Iterator iterator( ) return new LinkedListIterator( 0 ); * Obtains a ListIterator object used to traverse the collection bidirectionally. * @return an iterator positioned prior to the requested element. * @param idx the index to start the iterator. Use size() to do complete * reverse traversal. Use 0 to do complete forward traversal. public ListIterator listiterator( int idx ) return new LinkedListIterator( idx ); Listas - 19 LinkedListIterator private class LinkedListIterator implements ListIterator private Node current; private Node lastvisited = null; private boolean lastmovewasprev = false; private int expectedmodcount = modcount; public LinkedListIterator( int idx ) current = getnode( idx ); public boolean hasnext( ) if( expectedmodcount!= modcount ) throw new ConcurrentModificationException( ); return current!= endmarker; Listas - 20 Listas-10
LinkedListIterator public Object next( ) if(!hasnext( ) ) throw new NoSuchElementException( ); Object nextitem = current.data; lastvisited = current; current = current.next; lastmovewasprev = false; return nextitem; public boolean hasprevious( ) if( expectedmodcount!= modcount ) throw new ConcurrentModificationException( ); return current!= beginmarker.next; Listas - 21 LinkedListIterator public void remove( ) if( expectedmodcount!= modcount ) throw new ConcurrentModificationException( ); if( lastvisited == null ) throw new IllegalStateException( ); LinkedList.this.remove( lastvisited ); lastvisited = null; if( lastmovewasprev ) current = current.next; expectedmodcount++; Listas - 22 Listas-11
LinkedListIterator public Object previous( ) if( expectedmodcount!= modcount ) throw new ConcurrentModificationException( ); if(!hasprevious( ) ) throw new NoSuchElementException( ); current = current.prev; lastvisited = current; lastmovewasprev = true; return current.data; Listas - 23 Listas-12