Lista Ligada. Nó de Lista Ligada

Documentos relacionados
Tabelas de Dispersão. Tabela de Dispersão

Orientação a Objetos AULA 09

Coleções em Java. Prof. Gustavo Willam Pereira ENG10082 Programação II. Créditos: Prof. Clayton Vieira Fraga Filho

Pilhas Filas e Listas

Capítulo VIII. Tipo Abstracto de Dados Dicionário. Acesso por Chave

ESTRUTURAS DE DADOS E ALGORITMOS LISTA LIGADA

ESTRUTURAS DE DADOS E ALGORITMOS LISTA LIGADA (ABORDAGEM RECURSIVA)

UNIP - Ciência da Computação e Sistemas de Informação. Estrutura de Dados. AULA 5 Pilhas

API e Coleções Java. Sérgio Luiz Ruivace Cerqueira

Programação Orientada a Objetos

Coleções. Prof. Marcelo Roberto Zorzan

4. Listas, Pilhas, e Filas

4. Listas, Pilhas, e Filas

Prova 2 PMR3201 1o. semestre 2015 Prof. Thiago Martins

Exercício de Estrutura de dados. Java Fila

Atividade 08 - Utilizando Collections - List

Java Util Collections - Interfaces Interfaces definidas

Coleções Avançadas. Programação Orientada a Objetos Java. Prof. Anselmo Cardoso Paiva Prof. Geraldo Braz Junior

Exercícios Suplementares de Programação Assembly da Cleópatra

JAVA COLLECTIONS API: LISTAS

Tipos de Dados Abstratos

Collections. Programação Orientada por Objetos (POO) Centro de Cálculo Instituto Superior de Engenharia de Lisboa

Listas Lineares Ordenadas

Algoritmos e Estruturas de Dados. Lição n.º 4 Pilhas

ALGORITMOS E ESTRUTURAS DE DADOS 2011/2012 DICIONÁRIO. Armanda Rodrigues 6 de Outubro 2011

Coleções POO. Prof. Marcio Delamaro

CES-11. Pilhas Definição Operações Filas. Operações Deques. Definição. Operações

Árvores binárias de pesquisa

Listas Ligadas, Pilhas e Filas

Programação Orientada a Objectos - P. Prata, P. Fazendeiro

Aplicações de vetores

Collections Framework

Estruturas de Dados Encadeadas

Tipos, Literais, Operadores

Tipos, Literais, Operadores

Interfaces POO. Prof. Marcio Delamaro

FILAS. As coisas de que uma fila é feita serão chamadas itens. Os itens podem ser números, strings, structs, etc., etc.

Computação II - Java Prof. Adriano Joaquim de Oliveira Cruz Aula Prática - Herança, Polimorfismo e Construtores

Prova 2 PMR3201 1o. semestre 2016 Prof. Thiago Martins

Java API. Giuliana Silva Bezerra

Estrutura de Dados Listas

Análise e Projeto Orientados por Objetos

Pilhas e Filas Encadeadas. Algoritmos e Estruturas de Dados I

Tabelas de Dispersão. Estrutura de Dados e Algoritmos

Paradigmas de Programação

Programação Estruturada e Orientada a Objetos

Interfaces. Interfaces: Exemplo. ! São um mecanismo poderoso para ter bons desenhos pois permitem separar contratos das implementações

Algoritmos e Estruturas de Dados. Lição n.º 3 Coleções: sacos, pilhas e filas

nome = n; cargo = c; salario = s; public void print() { System.out.println(nome cargo salario); public void aumento( double fator){

Algoritmos e Estruturas de Dados. Lição n.º 3 Coleções: sacos, pilhas e filas

Palavras Reservadas da Linguagem Java

ArrayList. null. null. null ... ArrayList<Ponto2D>

LISTA DUPLAMENTE ENCADEADA

Tipos Abstractos de Dados (TADs) e Java

Universidade de Mogi das Cruzes Implementação Orientada a Objetos - Profª. Danielle Martin. Guia da Sintaxe do Java

Lista encadeada class No { Coleções. Enumeration. Lista encadeada (continuação) Enumeration Exemplo usando a classe Lista anterior

Transcrição:

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