Lista Ligada. Nó de Lista Ligada

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

pior caso nas operações de manipulação é O(N) pior caso surge sistematicamente emusos correntes (ex: elementos previamente ordenados)

Orientação a Objetos AULA 09

LEIC-FEUP 2001/2002 Algoritmos e Estruturas de Dados 1. Árvores-1

PCC104 - Projeto e Análise de Algoritmos

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

capta a noção elementar de ordemde chegada no processamento de tarefas, além da ordem de chegada é típico atender à prioridade

Pilhas Filas e Listas

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

Iterator. Professor: Hyggo Almeida

ESTRUTURAS DE DADOS E ALGORITMOS LISTA LIGADA

Estruturas de dados dinâmicas e Genéricos. Capítulo 10

ESTRUTURAS DE DADOS E ALGORITMOS LISTA LIGADA (ABORDAGEM RECURSIVA)

Árvores Binárias de Pesquisa

Tipo de Dados Abstracto

Algoritmos e Estruturas de Dados 2006/2007

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

Coleções. Profa. Thienne Johnson EACH/USP

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

Programação Orientada a Objetos

Algoritmos e Estruturas de Dados 2005/2006

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

Coleções. João Paulo Q. dos Santos

Exercício de Estrutura de dados. Java Fila

Departamento de Ciência de Computadores Estruturas de Dados (CC114)

Atividade 08 - Utilizando Collections - List

Universidade Federal do Ma Curso de Ciência da Computação

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

Algoritmos e Estruturas de Dados 2009/2010

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

Tipos de Dados Abstractos Estruturas Lineares Listas

Quando uma função/método chama ela mesma Exemplo clássico: the factorial function

Algoritmos e Estruturas de Dados

Departamento de Ciência de Computadores Estruturas de Dados (CC114)

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

Listas Lineares Ordenadas

Departamento de Ciência de Computadores Estruturas de Dados (CC114)

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

Exame de Estruturas de Dados 2010.Junho.26

Java Collections Framework II

Aplicações de vetores

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

Árvores binárias de pesquisa

Exame de Admissão. Instituto Nacional de Pesquisas Espaciais 18 de setembro de 2018 A: GABARITO

Listas Ligadas, Pilhas e Filas

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

Aplicações de vetores

Collections Framework

2 Vectores de objectos

Estruturas de Dados Encadeadas

Departamento de Ciência de Computadores Estruturas de Dados (CC114)

Tipos, Literais, Operadores

Tipos, Literais, Operadores

Interfaces POO. Prof. Marcio Delamaro

ALGORITMOS E ESTRUTURAS DE DADOS 2011/2012 ANÁLISE DE ALGORITMOS. Armanda Rodrigues 3 de Outubro 2011

PMR Computação para Automação Exercício Programa Package BancoDeDados Prof. Dr. Fabio Gagliardi Cozman Prof. Dr.

01/06/2016 INF1636 PROGRAMAÇÃO ORIENTADA A OBJETOS. Programa Capítulo 15. Coleções. A Interface List. A Classe LinkedList. Exercício.

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

Desenvolvimento e Projeto de Aplicações Web

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

Algoritmos e Estruturas de Dados 1

Listas Ligadas, Pilhas e Filas

Filas de Prioridade. Uma fila de prioridade pode ser vista como uma generalização das filas com as seguintes duas operações:

Estrutura de Dados Listas

Análise e Projeto Orientados por Objetos

Pilhas e Filas Encadeadas. Algoritmos e Estruturas de Dados I

Testes de correção (de defeitos)

Tabelas de Dispersão. Estrutura de Dados e Algoritmos

Paradigmas de Programação

Programação Estruturada e Orientada a Objetos

Programação Orientada pelos Objetos B. Desenvolvimento orientado pelos objectos

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

A Relação de Subtipo e Tipos Genéricos

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

Técnicas Modernas em Compiladores

Listas Lineares. Algoritmos e Estruturas de Dados I. José Augusto Baranauskas Departamento de Física e Matemática FFCLRP-USP

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>

Estrutura de Dados e Algoritmos e Programação e Computadores II. Aula 4: Listas Estáticas e Dinâmicas

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

Listas Encadeadas. Fabrício J. Barth. BandTec - Faculdade de Tecnologia Bandeirantes

Programação por Objectos. 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