├── .classpath
├── .gitignore
├── .project
├── .vscode
├── extensions.json
└── settings.json
├── README.md
├── exercicios
├── 02-ExerciciosVetoresListas.pdf
├── 03-ExerciciosPilhas.pdf
├── 04-ExerciciosFilas.pdf
└── 05-ExerciciosListaEncadeada.pdf
└── src
└── com
└── loiane
└── estruturadados
├── base
└── EstruturaEstatica.java
├── fila
├── Fila.java
├── FilaComPrioridade.java
├── labs
│ ├── Documento.java
│ ├── Exer01.java
│ ├── Exer02.java
│ ├── Exer03.java
│ ├── Exer04.java
│ ├── PSAtendimento.java
│ ├── PSNovosPacientes.java
│ └── Pessoa.java
└── teste
│ ├── Aula19.java
│ ├── Aula20.java
│ ├── Aula21.java
│ ├── Aula22.java
│ ├── Aula23.java
│ ├── Aula24.java
│ ├── Aula25.java
│ ├── Classe1.java
│ ├── Interface1.java
│ └── Paciente.java
├── lista
├── ListaEncadeada.java
├── ListaEncadeadaImutavel.java
├── No.java
├── NoImutavel.java
├── labs
│ ├── Exer01.java
│ ├── Exer02.java
│ ├── Exer03.java
│ ├── Exer04.java
│ ├── Exer05.java
│ ├── FilaEncadeada.java
│ ├── PilhaEncadeada.java
│ └── Transacao.java
└── teste
│ ├── CompararNumero.java
│ └── ListaEncadeadaTeste.java
├── pilha
├── Pilha.java
├── labs
│ ├── Exer01.java
│ ├── Exer02.java
│ ├── Exer03.java
│ ├── Exer04.java
│ ├── Exer05.java
│ ├── Exer06.java
│ ├── Exer07.java
│ ├── Exer08.java
│ └── Livro.java
└── teste
│ ├── Aula13.java
│ ├── Aula14.java
│ ├── Aula15.java
│ ├── Aula16.java
│ ├── Aula17.java
│ └── Aula18.java
└── vetor
├── Lista.java
├── Lista2.java
├── Vetor.java
├── VetorObjetos.java
├── labs
├── Exer01.java
├── Exer02.java
├── Exer03.java
├── Exer04.java
├── Exer05.java
├── Exer06.java
└── Exer07.java
└── teste
├── Aula02.java
├── Aula03.java
├── Aula04.java
├── Aula05.java
├── Aula06.java
├── Aula07.java
├── Aula08.java
├── Aula09.java
├── Aula10.java
├── Aula11.java
├── Aula12.java
└── Contato.java
/.classpath:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /bin/
2 | .settings/*
--------------------------------------------------------------------------------
/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | estrutura-dados-algoritmos-java
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.jdt.core.javabuilder
10 |
11 |
12 |
13 |
14 |
15 | org.eclipse.jdt.core.javanature
16 |
17 |
18 |
19 | 1701622291663
20 |
21 | 30
22 |
23 | org.eclipse.core.resources.regexFilterMatcher
24 | node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__
25 |
26 |
27 |
28 |
29 |
--------------------------------------------------------------------------------
/.vscode/extensions.json:
--------------------------------------------------------------------------------
1 | {
2 | // See https://go.microsoft.com/fwlink/?LinkId=827846 to learn about workspace recommendations.
3 | // Extension identifier format: ${publisher}.${name}. Example: vscode.csharp
4 |
5 | // List of extensions which should be recommended for users of this workspace.
6 | "recommendations": [
7 | "vscjava.vscode-java-pack"
8 | ],
9 | // List of extensions recommended by VS Code that should not be recommended for users of this workspace.
10 | "unwantedRecommendations": [
11 |
12 | ]
13 | }
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "editor.fontSize": 16,
3 | "debug.console.fontSize": 14,
4 | "window.zoomLevel": 2
5 | }
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # estrutura-dados-algoritmos-java
2 | ☕ [PT-BR] Código fonte apresentado no curso de Estrutura de Dados e Algoritmos com Java
3 |
4 | Playlist: https://www.youtube.com/playlist?list=PLGxZ4Rq3BOBrgumpzz-l8kFMw2DLERdxi
5 |
6 | ### Listas de exercícios
7 | Os exercícios estão dentro da pasta `exercicios`:
8 | * [Exercicios Vetores (Arrays)](https://github.com/loiane/estrutura-dados-algoritmos-java/blob/master/exercicios/02-ExerciciosVetoresListas.pdf)
9 | * [Exercicios Pilhas (Stacks)](https://github.com/loiane/estrutura-dados-algoritmos-java/blob/master/exercicios/03-ExerciciosPilhas.pdf)
10 | * [Exercicios Filas (Queues)](https://github.com/loiane/estrutura-dados-algoritmos-java/blob/master/exercicios/04-ExerciciosFilas.pdf)
11 | * [Exercicios Listas (Linked List)](https://github.com/loiane/estrutura-dados-algoritmos-java/blob/master/exercicios/05-ExerciciosListaEncadeada.pdf)
12 |
13 | ### Certificado
14 |
15 | O certificado de participação do curso está disponível para as pessoas que concluíram o curso no portal [https://loiane.training](https://loiane.training/).
16 |
--------------------------------------------------------------------------------
/exercicios/02-ExerciciosVetoresListas.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loiane/estrutura-dados-algoritmos-java/66072fff52af39a763f3762113e3771d4dc011cc/exercicios/02-ExerciciosVetoresListas.pdf
--------------------------------------------------------------------------------
/exercicios/03-ExerciciosPilhas.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loiane/estrutura-dados-algoritmos-java/66072fff52af39a763f3762113e3771d4dc011cc/exercicios/03-ExerciciosPilhas.pdf
--------------------------------------------------------------------------------
/exercicios/04-ExerciciosFilas.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loiane/estrutura-dados-algoritmos-java/66072fff52af39a763f3762113e3771d4dc011cc/exercicios/04-ExerciciosFilas.pdf
--------------------------------------------------------------------------------
/exercicios/05-ExerciciosListaEncadeada.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/loiane/estrutura-dados-algoritmos-java/66072fff52af39a763f3762113e3771d4dc011cc/exercicios/05-ExerciciosListaEncadeada.pdf
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/base/EstruturaEstatica.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.base;
2 |
3 | public class EstruturaEstatica {
4 |
5 | protected T[] elementos;
6 | protected int tamanho;
7 |
8 | @SuppressWarnings("unchecked")
9 | public EstruturaEstatica(int capacidade){
10 | this.elementos = (T[]) new Object[capacidade]; //solução do livro effective Java
11 | this.tamanho = 0;
12 | }
13 |
14 | public EstruturaEstatica(){
15 | this(10);
16 | }
17 |
18 | public boolean estaVazia(){
19 | return this.tamanho == 0;
20 | }
21 |
22 | protected boolean adiciona(T elemento) {
23 | this.aumentaCapacidade();
24 | if (this.tamanho < this.elementos.length){
25 | this.elementos[this.tamanho] = elemento;
26 | this.tamanho++;
27 | return true;
28 | }
29 | return false;
30 | }
31 |
32 | protected boolean adiciona(int posicao, T elemento){
33 |
34 | if (posicao < 0 || posicao > tamanho){
35 | throw new IllegalArgumentException("Posição inválida");
36 | }
37 |
38 | this.aumentaCapacidade();
39 |
40 | //mover todos os elementos
41 | for (int i=this.tamanho-1; i>=posicao; i--){
42 | this.elementos[i+1] = this.elementos[i];
43 | }
44 | this.elementos[posicao] = elemento;
45 | this.tamanho++;
46 |
47 | return true;
48 | }
49 |
50 | protected void remove(int posicao){
51 | if (!(posicao >= 0 && posicao < tamanho)){
52 | throw new IllegalArgumentException("Posicao inválida");
53 | }
54 | for (int i=posicao; i0){
87 | s.append(this.elementos[this.tamanho-1]);
88 | }
89 |
90 | s.append("]");
91 |
92 | return s.toString();
93 | }
94 | }
95 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/fila/Fila.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.fila;
2 |
3 | import com.loiane.estruturadados.base.EstruturaEstatica;
4 |
5 | public class Fila extends EstruturaEstatica{
6 |
7 | public Fila(){
8 | super();
9 | }
10 |
11 | public Fila(int capacidade){
12 | super(capacidade);
13 | }
14 |
15 | public void enfileira(T elemento){
16 | //this.elementos[this.tamanho] = elemento;
17 | //this.tamanho++;
18 |
19 | //this.elementos[this.tamanho++] = elemento;
20 |
21 | this.adiciona(elemento);
22 | }
23 |
24 | public T espiar(){
25 |
26 | if (this.estaVazia()){
27 | return null;
28 | }
29 |
30 | return this.elementos[0];
31 | }
32 |
33 | public T desenfileira(){
34 |
35 | final int POS = 0;
36 |
37 | if (this.estaVazia()){
38 | return null;
39 | }
40 |
41 | T elementoASerRemovido = this.elementos[POS];
42 |
43 | this.remove(POS);
44 |
45 | return elementoASerRemovido;
46 |
47 | }
48 | }
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/fila/FilaComPrioridade.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.fila;
2 |
3 | public class FilaComPrioridade extends Fila{
4 |
5 | public void enfileira(T elemento){
6 |
7 | Comparable chave = (Comparable) elemento;
8 |
9 | int i;
10 | for (i=0; i filaImpressora = new Fila<>();
10 |
11 | filaImpressora.enfileira(new Documento("A", 1));
12 | filaImpressora.enfileira(new Documento("B", 2));
13 | filaImpressora.enfileira(new Documento("C", 3));
14 | filaImpressora.enfileira(new Documento("D", 7));
15 | filaImpressora.enfileira(new Documento("E", 9));
16 |
17 | while (!filaImpressora.estaVazia()) {
18 | Documento doc = filaImpressora.desenfileira();
19 | System.out.println("Imprimindo documento " + doc.getNome());
20 | try {
21 | Thread.sleep(200 * doc.getNumFolhas());
22 | } catch (InterruptedException e) {
23 | e.printStackTrace();
24 | }
25 | }
26 |
27 | System.out.println("Todos os documentos foram impressos.");
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/fila/labs/Exer02.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.fila.labs;
2 |
3 | import com.loiane.estruturadados.fila.Fila;
4 |
5 | public class Exer02 {
6 |
7 | public static void main(String[] args) {
8 |
9 | Fila regular = new Fila<>();
10 | Fila prioridade = new Fila<>();
11 |
12 | final int MAX_PRIORIDADE = 3;
13 |
14 | regular.enfileira("Pessoa 1");
15 | regular.enfileira("Pessoa 2");
16 | regular.enfileira("Pessoa 3");
17 | prioridade.enfileira("Pessoa 1P");
18 | prioridade.enfileira("Pessoa 2P");
19 | prioridade.enfileira("Pessoa 3P");
20 | prioridade.enfileira("Pessoa 4P");
21 | prioridade.enfileira("Pessoa 5P");
22 | regular.enfileira("Pessoa 4");
23 | regular.enfileira("Pessoa 5");
24 | regular.enfileira("Pessoa 6");
25 | regular.enfileira("Pessoa 7");
26 | regular.enfileira("Pessoa 8");
27 |
28 | while (!regular.estaVazia() || !prioridade.estaVazia()) {
29 |
30 | int cont = 0;
31 |
32 | while(!prioridade.estaVazia() && cont < MAX_PRIORIDADE) {
33 | atendePessoa(prioridade);
34 | cont++;
35 | }
36 |
37 | if (!regular.estaVazia()) {
38 | atendePessoa(regular);
39 | }
40 |
41 | if (prioridade.estaVazia()) {
42 | while (!regular.estaVazia()) {
43 | atendePessoa(regular);
44 | }
45 | }
46 | }
47 | }
48 |
49 | public static void atendePessoa(Fila fila) {
50 | String pessoaAtendida = fila.desenfileira();
51 | System.out.println(pessoaAtendida + " foi atendida.");
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/fila/labs/Exer03.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.fila.labs;
2 |
3 | import com.loiane.estruturadados.fila.FilaComPrioridade;
4 |
5 | public class Exer03 {
6 |
7 | public static final int VERDE = 2;
8 | public static final int AMARELO = 1;
9 | public static final int VERMELHO = 0;
10 |
11 | public static void main(String[] args) {
12 |
13 | FilaComPrioridade fila = new FilaComPrioridade<>();
14 | fila.enfileira(new Pessoa("1", VERDE));
15 | fila.enfileira(new Pessoa("2", AMARELO));
16 | fila.enfileira(new Pessoa("3", VERMELHO));
17 | fila.enfileira(new Pessoa("4", VERDE));
18 | fila.enfileira(new Pessoa("5", VERDE));
19 | fila.enfileira(new Pessoa("6", VERMELHO));
20 |
21 | PSAtendimento atendimento = new PSAtendimento(fila);
22 | PSNovosPacientes pacientes = new PSNovosPacientes(fila);
23 |
24 | Thread t1 = new Thread(atendimento);
25 | Thread t2 = new Thread(pacientes);
26 |
27 | t1.start();
28 | t2.start();
29 | }
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/fila/labs/Exer04.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.fila.labs;
2 |
3 | import java.util.Random;
4 |
5 | import com.loiane.estruturadados.fila.Fila;
6 |
7 | public class Exer04 {
8 |
9 | public static void main(String[] args) {
10 |
11 | Fila fila = new Fila<>();
12 |
13 | for (int i=0; i<10; i++) {
14 | fila.enfileira(i);
15 | }
16 |
17 | Random aleatorio = new Random();
18 | int num = 0;
19 | while (num == 0) {
20 | num = aleatorio.nextInt(10);
21 | }
22 |
23 | System.out.println("Número = " + num);
24 |
25 | while (fila.tamanho() > 1) {
26 | for (int i=0; i fila;
8 |
9 | public PSAtendimento(FilaComPrioridade fila) {
10 | super();
11 | this.fila = fila;
12 | }
13 |
14 | @Override
15 | public void run() {
16 |
17 | while (!fila.estaVazia()) {
18 | try {
19 | System.out.println(fila.desenfileira() + " atendida.");
20 | Thread.sleep(5000);
21 | } catch (InterruptedException e) {
22 | e.printStackTrace();
23 | }
24 | }
25 |
26 | System.out.println("Atendimento concluído.");
27 |
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/fila/labs/PSNovosPacientes.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.fila.labs;
2 |
3 | import java.util.Random;
4 |
5 | import com.loiane.estruturadados.fila.FilaComPrioridade;
6 |
7 | public class PSNovosPacientes implements Runnable {
8 |
9 | private FilaComPrioridade fila;
10 | private int cont = 7;
11 | private Random prioridade = new Random();
12 |
13 | public PSNovosPacientes(FilaComPrioridade fila) {
14 | super();
15 | this.fila = fila;
16 | }
17 |
18 | @Override
19 | public void run() {
20 |
21 | for (int i=0; i<8; i++) {
22 | try {
23 | Thread.sleep(8000);
24 | Pessoa p = new Pessoa("" + cont, prioridade.nextInt(3));
25 | fila.enfileira(p);
26 | cont++;
27 | System.out.println(p + " enfileirada.");
28 | } catch (InterruptedException e) {
29 | e.printStackTrace();
30 | }
31 | }
32 |
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/fila/labs/Pessoa.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.fila.labs;
2 |
3 | public class Pessoa implements Comparable {
4 |
5 | private String nome;
6 | private int prioridade;
7 |
8 | public Pessoa(String nome, int prioridade) {
9 | super();
10 | this.nome = nome;
11 | this.prioridade = prioridade;
12 | }
13 | public String getNome() {
14 | return nome;
15 | }
16 | public void setNome(String nome) {
17 | this.nome = nome;
18 | }
19 | public int getPrioridade() {
20 | return prioridade;
21 | }
22 | public void setPrioridade(int prioridade) {
23 | this.prioridade = prioridade;
24 | }
25 |
26 | @Override
27 | public int compareTo(Pessoa o) {
28 |
29 | if (prioridade > o.prioridade) {
30 | return 1;
31 | } else if (prioridade < o.prioridade) {
32 | return -1;
33 | }
34 | return 0;
35 | }
36 | @Override
37 | public String toString() {
38 | return "Pessoa [nome=" + nome + ", prioridade=" + prioridade + "]";
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/fila/teste/Aula19.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.fila.teste;
2 |
3 | import com.loiane.estruturadados.fila.Fila;
4 |
5 | public class Aula19 {
6 |
7 | public static void main(String[] args) {
8 |
9 | Fila fila = new Fila<>();
10 |
11 | System.out.println(fila.estaVazia()); //true
12 | System.out.println(fila.tamanho()); // 0
13 |
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/fila/teste/Aula20.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.fila.teste;
2 |
3 | import com.loiane.estruturadados.fila.Fila;
4 |
5 | public class Aula20 {
6 |
7 | public static void main(String[] args) {
8 |
9 | Fila fila = new Fila<>();
10 |
11 | fila.enfileira(1);
12 | fila.enfileira(2);
13 | fila.enfileira(3);
14 |
15 | System.out.println(fila.estaVazia()); //false
16 | System.out.println(fila.tamanho()); //3
17 |
18 | System.out.println(fila.toString());
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/fila/teste/Aula21.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.fila.teste;
2 |
3 | import com.loiane.estruturadados.fila.Fila;
4 |
5 | public class Aula21 {
6 |
7 | public static void main(String[] args) {
8 |
9 | Fila fila = new Fila<>();
10 |
11 | fila.enfileira(3);
12 | fila.enfileira(1);
13 | fila.enfileira(2);
14 |
15 | System.out.println(fila.espiar());
16 |
17 | System.out.println(fila.toString());
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/fila/teste/Aula22.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.fila.teste;
2 |
3 | import com.loiane.estruturadados.fila.Fila;
4 |
5 | public class Aula22 {
6 |
7 | public static void main(String[] args) {
8 |
9 | Fila fila = new Fila<>();
10 |
11 | fila.enfileira(1);
12 | fila.enfileira(2);
13 | fila.enfileira(3);
14 |
15 | System.out.println(fila);
16 |
17 | System.out.println(fila.desenfileira());
18 |
19 | System.out.println(fila);
20 |
21 | System.out.println(fila.desenfileira());
22 |
23 | System.out.println(fila);
24 |
25 | System.out.println(fila.desenfileira());
26 |
27 | System.out.println(fila);
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/fila/teste/Aula23.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.fila.teste;
2 |
3 | import java.util.LinkedList;
4 | import java.util.Queue;
5 |
6 | public class Aula23 {
7 |
8 | public static void main(String[] args) {
9 |
10 | Queue fila = new LinkedList<>();
11 |
12 | fila.add(1); //enqueue - enfileirar
13 | fila.add(2);
14 |
15 | System.out.println(fila);
16 |
17 | System.out.println(fila.peek()); //espiar
18 |
19 | System.out.println(fila.remove()); //dequeue - desenfileirar
20 |
21 | System.out.println(fila);
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/fila/teste/Aula24.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.fila.teste;
2 |
3 | import com.loiane.estruturadados.fila.FilaComPrioridade;
4 |
5 | public class Aula24 {
6 |
7 | public static void main(String[] args) {
8 |
9 | FilaComPrioridade fila = new FilaComPrioridade<>();
10 |
11 | fila.enfileira(new Paciente("A", 2));
12 | fila.enfileira(new Paciente("C", 1));
13 | fila.enfileira(new Paciente("B", 3));
14 |
15 | System.out.println(fila); //1 2 3 e nao 1 3 2
16 |
17 | System.out.println(fila.desenfileira());
18 |
19 | System.out.println(fila);
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/fila/teste/Aula25.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.fila.teste;
2 |
3 | import java.util.Comparator;
4 | import java.util.PriorityQueue;
5 | import java.util.Queue;
6 |
7 | public class Aula25 {
8 |
9 | public static void main(String[] args) {
10 |
11 | Queue filaComPrioridade = new PriorityQueue<>(
12 | new Comparator() {
13 | @Override
14 | public int compare(Paciente p1, Paciente p2) {
15 | return Integer.valueOf(p1.getPrioridade()).compareTo(p2.getPrioridade());
16 | }
17 | }
18 | );
19 |
20 | filaComPrioridade.add(new Paciente("A", 2));
21 | filaComPrioridade.add(new Paciente("B", 1));
22 |
23 | System.out.println(filaComPrioridade);
24 |
25 | }
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/fila/teste/Classe1.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.fila.teste;
2 |
3 | public class Classe1 implements Interface1{
4 |
5 | public void teste(){
6 |
7 | }
8 |
9 | @Override
10 | public void adiciona() {
11 | // TODO Auto-generated method stub
12 |
13 | }
14 |
15 | @Override
16 | public void remove() {
17 | // TODO Auto-generated method stub
18 |
19 | }
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/fila/teste/Interface1.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.fila.teste;
2 |
3 | public interface Interface1 {
4 |
5 | public void adiciona();
6 |
7 | public void remove();
8 | }
9 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/fila/teste/Paciente.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.fila.teste;
2 |
3 | public class Paciente implements Comparable {
4 |
5 | private String nome;
6 | private int prioridade;
7 |
8 | public Paciente(String nome, int prioridade) {
9 | super();
10 | this.nome = nome;
11 | this.prioridade = prioridade;
12 | }
13 |
14 | public Paciente(){}
15 |
16 | public String getNome() {
17 | return nome;
18 | }
19 | public void setNome(String nome) {
20 | this.nome = nome;
21 | }
22 | public int getPrioridade() {
23 | return prioridade;
24 | }
25 | public void setPrioridade(int prioridade) {
26 | this.prioridade = prioridade;
27 | }
28 |
29 | @Override
30 | public int compareTo(Paciente o) {
31 |
32 | //obj1 > obj2 retorna > 0 (1)
33 | //ojb1 < obj2 retorna < 0 (-1)
34 |
35 | if (this.prioridade > o.getPrioridade()){
36 | return 1;
37 | } else if (this.prioridade < o.getPrioridade()){
38 | return -1;
39 | }
40 |
41 | return 0;
42 | }
43 |
44 | @Override
45 | public String toString() {
46 | return "Paciente [nome=" + nome + ", prioridade=" + prioridade + "]";
47 | }
48 |
49 |
50 | }
51 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/lista/ListaEncadeada.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.lista;
2 |
3 | import java.util.Comparator;
4 |
5 | public class ListaEncadeada {
6 |
7 | private No inicio;
8 | private No ultimo;
9 | private int tamanho = 0;
10 |
11 | private final int NAO_ENCONTRADO = -1;
12 | private final String NAO_EXISTE = "Posição não existe.";
13 | private final String LISTA_VAZIA = "Lista está vazia.";
14 | private static final int MENOR = -1;
15 | private static final int IGUAL_MAIOR = 0;
16 |
17 | public void adiciona(T elemento) {
18 | No celula = new No(elemento);
19 | if (this.tamanho == 0) {
20 | this.inicio = celula;
21 | } else {
22 | this.ultimo.setProximo(celula);
23 | }
24 | this.ultimo = celula;
25 | this.tamanho++;
26 | }
27 |
28 | public void adicionaInicio(T elemento) {
29 | if (this.tamanho == 0) {
30 | No novoNo = new No<>(elemento);
31 | this.inicio = novoNo;
32 | this.ultimo = novoNo;
33 | } else {
34 | No novoNo = new No<>(elemento, this.inicio);
35 | this.inicio = novoNo;
36 | }
37 | this.tamanho++;
38 | }
39 |
40 | public void adiciona(int posicao, T elemento) {
41 |
42 | if (this.posicaoNaoExiste(posicao)) {
43 | throw new IllegalArgumentException(NAO_EXISTE);
44 | }
45 |
46 | if (posicao == 0) { // está vazia
47 | this.adicionaInicio(elemento);
48 | } else if (posicao == this.tamanho) { // adiciona
49 | this.adiciona(elemento);
50 | } else { // meio
51 | No noAnterior = this.buscaNo(posicao);
52 | No proximoNo = noAnterior.getProximo();
53 | No novoNo = new No<>(elemento, proximoNo);
54 | noAnterior.setProximo(novoNo);
55 | this.tamanho++;
56 | }
57 | }
58 |
59 | public T removeInicio() {
60 | if (this.tamanho == 0) {
61 | throw new RuntimeException(LISTA_VAZIA);
62 | }
63 | T removido = this.inicio.getElemento();
64 | this.inicio = this.inicio.getProximo();
65 | this.tamanho--;
66 |
67 | if (this.tamanho == 0) {
68 | this.ultimo = null;
69 | }
70 |
71 | return removido;
72 | }
73 |
74 | public T removeFinal() {
75 | if (this.tamanho == 0) {
76 | throw new RuntimeException(LISTA_VAZIA);
77 | }
78 | if (this.tamanho == 1) {
79 | return this.removeInicio();
80 | }
81 | No penultimoNo = this.buscaNo(this.tamanho - 2);
82 | T removido = penultimoNo.getProximo().getElemento();
83 | penultimoNo.setProximo(null);
84 | this.ultimo = penultimoNo;
85 | this.tamanho--;
86 |
87 | return removido;
88 | }
89 |
90 | private boolean posicaoNaoExiste(int posicao) {
91 | return !(posicao >= 0 && posicao <= this.tamanho);
92 | }
93 |
94 | public T remove(int posicao) {
95 |
96 | if (this.posicaoNaoExiste(posicao)) {
97 | throw new IllegalArgumentException(NAO_EXISTE);
98 | }
99 |
100 | if (posicao == 0) {
101 | return this.removeInicio();
102 | }
103 | if (posicao == this.tamanho - 1) {
104 | return this.removeFinal();
105 | }
106 | No noAnterior = this.buscaNo(posicao - 1);
107 | No atual = noAnterior.getProximo();
108 | No proximo = atual.getProximo();
109 | noAnterior.setProximo(proximo);
110 | atual.setProximo(null);
111 | this.tamanho--;
112 | return atual.getElemento();
113 | }
114 |
115 | public int getTamanho() {
116 | return this.tamanho;
117 | }
118 |
119 | public void limpa() {
120 |
121 | for (No atual = this.inicio; atual != null;) {
122 | No proximo = atual.getProximo();
123 | atual.setElemento(null);
124 | atual.setProximo(null);
125 | atual = proximo;
126 | }
127 |
128 | this.inicio = null;
129 | this.ultimo = null;
130 | this.tamanho = 0;
131 | }
132 |
133 | private No buscaNo(int posicao) {
134 |
135 | if (this.posicaoNaoExiste(posicao)) {
136 | throw new IllegalArgumentException(NAO_EXISTE);
137 | }
138 |
139 | No noAtual = this.inicio;
140 | for (int i = 0; i < posicao; i++) {
141 | noAtual = noAtual.getProximo();
142 | }
143 |
144 | return noAtual;
145 | }
146 |
147 | public T buscaPorPosicao(int posicao) {
148 | return this.buscaNo(posicao).getElemento();
149 | }
150 |
151 | public int busca(T elemento) {
152 |
153 | No noAtual = this.inicio;
154 | int pos = 0;
155 |
156 | while (noAtual != null) {
157 |
158 | if (noAtual.getElemento().equals(elemento)) {
159 | return pos;
160 | }
161 | pos++;
162 | noAtual = noAtual.getProximo();
163 | }
164 |
165 | return NAO_ENCONTRADO;
166 | }
167 |
168 | public void adicionaOrdenado(T elemento, Comparator comparator) {
169 | if (this.tamanho == 0) { // esta vazia
170 | this.adicionaInicio(elemento);
171 | } else if (comparator.compare(this.inicio.getElemento(), elemento) >= IGUAL_MAIOR) {
172 | this.adicionaInicio(elemento);
173 | } else {
174 | No atual = this.inicio;
175 | while (atual.getProximo() != null
176 | && comparator.compare(atual.getProximo().getElemento(), elemento) == MENOR) {
177 | atual = atual.getProximo();
178 | }
179 | No celula = new No<>(elemento, atual.getProximo());
180 | atual.setProximo(celula);
181 | this.tamanho++;
182 | }
183 | }
184 |
185 | @SuppressWarnings("unchecked")
186 | public T[] transformaArray() {
187 | if (this.tamanho == 0) {
188 | return (T[]) new Object[0];
189 | }
190 | Object[] vetor = new Object[this.tamanho];
191 | No atual = this.inicio;
192 | for (int i = 0; i < this.tamanho; i++) {
193 | vetor[i] = atual.getElemento();
194 | atual = atual.getProximo();
195 | }
196 | return (T[]) vetor;
197 | }
198 |
199 | public void inverte() { // reverse
200 | No atual = this.inicio;
201 | No proximo = null;
202 | No anterior = null;
203 | while (atual != null) {
204 | proximo = atual.getProximo();
205 | atual.setProximo(anterior);
206 | anterior = atual;
207 | atual = proximo;
208 | }
209 | this.inicio = anterior;
210 | }
211 |
212 | @Override
213 | public String toString() {
214 |
215 | // [1, 2, 3, 4]
216 |
217 | if (this.tamanho == 0) {
218 | return "[]";
219 | }
220 |
221 | StringBuilder builder = new StringBuilder("[");
222 | // builder.append("ListaEncadeada [inicio=").append(inicio).append("]");
223 |
224 | No atual = this.inicio;
225 | for (int i = 0; i < this.tamanho - 1; i++) {
226 | builder.append(atual.getElemento()).append(",");
227 | atual = atual.getProximo();
228 | }
229 | builder.append(atual.getElemento()).append("]");
230 | /*
231 | * builder.append(atual.getElemento()).append(",");
232 | * while (atual.getProximo() != null) {
233 | * atual = atual.getProximo();
234 | * builder.append(atual.getElemento()).append(",");
235 | * }
236 | */
237 |
238 | return builder.toString();
239 | }
240 |
241 | }
242 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/lista/ListaEncadeadaImutavel.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.lista;
2 |
3 | /**
4 | * ListaEncadeadaImutavel
5 | */
6 | public class ListaEncadeadaImutavel {
7 |
8 | private NoImutavel primeira;
9 | private NoImutavel ultima;
10 | private int tamanho = 0;
11 |
12 | public void adiciona(final T elemento){
13 | NoImutavel celula = new NoImutavel<>(elemento);
14 | if (this.tamanho == 0){
15 | this.primeira = celula;
16 | } else {
17 | this.ultima.setProxima(celula);
18 | this.ultima = celula;
19 |
20 | }
21 | this.ultima = celula;
22 | this.tamanho++;
23 | }
24 |
25 | private NoImutavel buscaCelula(int posicao){
26 | if (!(posicao >= 0 && posicao < this.tamanho)){
27 | throw new IllegalArgumentException("Posicao inválida");
28 | }
29 |
30 | NoImutavel atual = this.primeira;
31 | for (int i=0; i atual = this.primeira;
44 | int pos = 0;
45 |
46 | while (atual != null){
47 | if (atual.getElemento().equals(elemento)) {
48 | return pos;
49 | }
50 | pos++;
51 | atual = atual.getProxima();
52 | }
53 |
54 | return -1;
55 | }
56 |
57 | @Override
58 | public String toString() {
59 |
60 | if(this.tamanho == 0){
61 | return "[]";
62 | }
63 |
64 | StringBuilder builder = new StringBuilder();
65 | NoImutavel atual = this.primeira;
66 |
67 | for (int i = 0; i < this.tamanho - 1; i++) {
68 | builder.append(atual.getElemento());
69 | builder.append(",\n");
70 | atual = atual.getProxima();
71 | }
72 |
73 | builder.append(atual.getElemento());
74 |
75 | return builder.toString();
76 | }
77 |
78 | public int getTamanho() {
79 | return tamanho;
80 | }
81 |
82 | @SuppressWarnings("unchecked")
83 | public T[] transformaArray() {
84 | if (this.tamanho == 0) {
85 | return (T[]) new Object[0];
86 | }
87 | Object[] vetor = new Object[this.tamanho];
88 | NoImutavel atual = this.primeira;
89 | for (int i = 0; i < this.tamanho; i++) {
90 | vetor[i] = atual.getElemento();
91 | atual = atual.getProxima();
92 | }
93 | return (T[]) vetor;
94 | }
95 |
96 | }
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/lista/No.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.lista;
2 |
3 | public class No {
4 |
5 | private T elemento;
6 | private No proximo;
7 |
8 | public No(T elemento) {
9 | this.elemento = elemento;
10 | this.proximo = null;
11 | }
12 |
13 | public No(T elemento, No proximo) {
14 | this.elemento = elemento;
15 | this.proximo = proximo;
16 | }
17 |
18 | public T getElemento() {
19 | return elemento;
20 | }
21 | public void setElemento(T elemento) {
22 | this.elemento = elemento;
23 | }
24 | public No getProximo() {
25 | return proximo;
26 | }
27 | public void setProximo(No proximo) {
28 | this.proximo = proximo;
29 | }
30 |
31 | @Override
32 | public String toString() {
33 | StringBuilder builder = new StringBuilder();
34 | builder.append("No [elemento=").append(elemento).append(", proximo=").append(proximo).append("]");
35 | return builder.toString();
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/lista/NoImutavel.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.lista;
2 |
3 | public class NoImutavel {
4 |
5 | private final T elemento;
6 | private NoImutavel proxima;
7 |
8 | public NoImutavel(final T elemento) {
9 | super();
10 | this.elemento = elemento;
11 | this.proxima = null;
12 | }
13 |
14 | public T getElemento() {
15 | return elemento;
16 | }
17 |
18 | public NoImutavel getProxima() {
19 | return proxima;
20 | }
21 |
22 | public void setProxima(final NoImutavel proxima) {
23 | this.proxima = proxima;
24 | }
25 |
26 | @Override
27 | public String toString() {
28 | return "No [elemento=" + elemento + ", proxima=" + proxima + "]";
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/lista/labs/Exer01.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.lista.labs;
2 |
3 | import java.util.Arrays;
4 | import java.util.LinkedList;
5 |
6 | import com.loiane.estruturadados.lista.ListaEncadeada;
7 |
8 | public class Exer01 {
9 |
10 | public static void main(String[] args) {
11 | ListaEncadeada lista = new ListaEncadeada<>();
12 | for (int i=1; i<=10; i++) {
13 | lista.adiciona(i);
14 | }
15 |
16 | System.out.println(lista);
17 |
18 | System.out.println(Arrays.toString(transformaArray(lista)));
19 |
20 | System.out.println(Arrays.toString(lista.transformaArray()));
21 |
22 | LinkedList list = new LinkedList<>();
23 | for (int i=1; i<=10; i++) {
24 | list.add(i);
25 | }
26 | }
27 |
28 | public static int[] transformaArray(ListaEncadeada lista) {
29 | int tamanho = lista.getTamanho();
30 | int[] vetor = new int[tamanho];
31 | for (int i=0; i lista = new ListaEncadeada<>();
14 | for (int i=1; i<=10; i++) {
15 | lista.adiciona(""+i);
16 | }
17 | System.out.println(lista);
18 |
19 | lista.inverte();
20 | System.out.println(lista);
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/lista/labs/Exer03.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.lista.labs;
2 |
3 | public class Exer03 {
4 |
5 | public static void main(String[] args) {
6 |
7 | PilhaEncadeada pilha = new PilhaEncadeada<>();
8 |
9 | for (int i=0; i<10; i++) {
10 | pilha.empilha(i);
11 | }
12 |
13 | System.out.println(pilha);
14 |
15 | System.out.println(pilha.desempilha());
16 | System.out.println(pilha.desempilha());
17 | System.out.println(pilha.desempilha());
18 |
19 | System.out.println(pilha);
20 | System.out.println(pilha.estaVazia());
21 | System.out.println(pilha.topo());
22 | System.out.println(pilha.tamanho());
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/lista/labs/Exer04.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.lista.labs;
2 |
3 | public class Exer04 {
4 | public static void main(String[] args) {
5 | FilaEncadeada fila = new FilaEncadeada<>();
6 |
7 | for (int i=0; i<10; i++) {
8 | fila.enfileira(i);
9 | }
10 |
11 | System.out.println(fila);
12 |
13 | System.out.println(fila.desenfileira());
14 |
15 | System.out.println(fila.espiar());
16 |
17 | System.out.println(fila);
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/lista/labs/Exer05.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.lista.labs;
2 |
3 | import java.time.LocalDate;
4 |
5 | import com.loiane.estruturadados.lista.ListaEncadeadaImutavel;
6 |
7 | /**
8 | * Escreva um programa que será usado para acompanhar os passos da venda de um
9 | * automóvel e/ou imóvel. Por exemplo, o automável é comprado inicialmente pela
10 | * pessoa A. Inserimos na lista um nó que representa essa informação, como
11 | * descrição do veículo, identificador, preço de compra, data de compra,
12 | * dono(a).
13 | */
14 | public class Exer05 {
15 | public static void main(String[] args) {
16 | ListaEncadeadaImutavel lista = new ListaEncadeadaImutavel<>();
17 |
18 | Transacao compra = new Transacao(1, 1, "Compra veiculo novo", 30000, LocalDate.now(), "Maria");
19 | lista.adiciona(compra);
20 |
21 | lista.adiciona(new Transacao(2, 2, "Venda", 25000, LocalDate.now(), "João"));
22 |
23 | System.out.println(lista);
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/lista/labs/FilaEncadeada.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.lista.labs;
2 |
3 | import com.loiane.estruturadados.lista.ListaEncadeada;
4 |
5 | public class FilaEncadeada {
6 |
7 | private ListaEncadeada elementos;
8 |
9 | FilaEncadeada() {
10 | this.elementos = new ListaEncadeada<>();
11 | }
12 |
13 | public void enfileira(T elemento) {
14 | this.elementos.adiciona(elemento);
15 | }
16 |
17 | public T espiar() {
18 | if (this.elementos.getTamanho() == 0) {
19 | return null;
20 | }
21 | return this.elementos.buscaPorPosicao(0);
22 | }
23 |
24 | public T desenfileira() {
25 | if (this.elementos.getTamanho() == 0) {
26 | return null;
27 | }
28 | return this.elementos.removeInicio();
29 | }
30 |
31 | public String toString() {
32 | return this.elementos.toString();
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/lista/labs/PilhaEncadeada.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.lista.labs;
2 |
3 | import com.loiane.estruturadados.lista.ListaEncadeada;
4 |
5 | public class PilhaEncadeada {
6 |
7 | private ListaEncadeada elementos;
8 |
9 | PilhaEncadeada() {
10 | this.elementos = new ListaEncadeada<>();
11 | }
12 |
13 | public void empilha(T elemento) {
14 | this.elementos.adiciona(elemento);
15 | }
16 |
17 | public boolean estaVazia() {
18 | return this.tamanho() == 0;
19 | }
20 |
21 | public T topo() {
22 | if (this.estaVazia()) {
23 | return null;
24 | }
25 | return this.elementos.buscaPorPosicao(this.tamanho() - 1);
26 | }
27 |
28 | public int tamanho() {
29 | return this.elementos.getTamanho();
30 | }
31 |
32 | public T desempilha() {
33 | if (this.estaVazia()) {
34 | return null;
35 | }
36 | return this.elementos.removeFinal();
37 | }
38 |
39 | public String toString() {
40 | return this.elementos.toString();
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/lista/labs/Transacao.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.lista.labs;
2 |
3 | import java.time.LocalDate;
4 |
5 |
6 | public record Transacao(int idTransacao,
7 | int idVeiculo, String descricao, double preco,
8 | LocalDate data, String proprietario) {}
9 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/lista/teste/CompararNumero.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.lista.teste;
2 |
3 | import java.util.Comparator;
4 |
5 | public class CompararNumero implements Comparator {
6 |
7 | @Override
8 | public int compare(Integer o1, Integer o2) {
9 | if (o1.intValue() == o2.intValue()) return 0;
10 | return o1.intValue() < o2.intValue() ? -1 : 1;
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/lista/teste/ListaEncadeadaTeste.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.lista.teste;
2 |
3 | import java.util.LinkedList;
4 |
5 | import com.loiane.estruturadados.lista.ListaEncadeada;
6 |
7 | public class ListaEncadeadaTeste {
8 |
9 | public static void main(String[] args) {
10 | // testesIniciais();
11 | // adicionaInicio();
12 | // adicionaPosicao();
13 | // removeInicio();
14 | // removeFinal();
15 | // removePosicao();
16 | // insereOrdenado()
17 | testeLinkedList();
18 | }
19 |
20 | public static void testeLinkedList() {
21 | LinkedList lista = new LinkedList<>();
22 |
23 | lista.add(1);
24 | lista.addFirst(0);
25 | lista.addLast(3);
26 |
27 | System.out.println(lista.contains(1));
28 |
29 | lista.add(2, 2);
30 |
31 | System.out.println(lista);
32 |
33 | lista.remove();
34 | System.out.println(lista);
35 |
36 | lista.remove(0);
37 | lista.removeFirst();
38 | lista.removeLast();
39 | System.out.println(lista);
40 | }
41 |
42 | private static void insereOrdenado() {
43 | ListaEncadeada lista = new ListaEncadeada<>();
44 | CompararNumero comparator = new CompararNumero();
45 | lista.adicionaOrdenado(5, comparator);
46 | System.out.println(lista);
47 | lista.adicionaOrdenado(1, comparator);
48 | System.out.println(lista);
49 | lista.adicionaOrdenado(4, comparator);
50 | System.out.println(lista);
51 | lista.adicionaOrdenado(2, comparator);
52 | System.out.println(lista);
53 | lista.adicionaOrdenado(3, comparator);
54 | System.out.println(lista);
55 | lista.adicionaOrdenado(6, comparator);
56 | System.out.println(lista);
57 | lista.adicionaOrdenado(5, comparator);
58 | System.out.println(lista);
59 | }
60 |
61 | public static void removePosicao() {
62 | ListaEncadeada lista = new ListaEncadeada<>();
63 | lista.adiciona(1);
64 | lista.adiciona(2);
65 | lista.adiciona(3);
66 | lista.adiciona(4);
67 | lista.adiciona(5);
68 |
69 | System.out.println("Elemento removido: " + lista.remove(4));
70 | System.out.println("Lista: " + lista);
71 |
72 | }
73 |
74 | public static void removeFinal() {
75 | ListaEncadeada lista = new ListaEncadeada<>();
76 |
77 | // lista.removeFinal();
78 |
79 | lista.adiciona(1);
80 | lista.adiciona(2);
81 | lista.adiciona(3);
82 |
83 | System.out.println("Elemento removido: " + lista.removeFinal());
84 | System.out.println("Lista: " + lista);
85 |
86 | System.out.println("Elemento removido: " + lista.removeFinal());
87 | System.out.println("Lista: " + lista);
88 |
89 | System.out.println("Elemento removido: " + lista.removeFinal());
90 | System.out.println("Lista: " + lista);
91 | }
92 |
93 | public static void removeInicio() {
94 | ListaEncadeada lista = new ListaEncadeada<>();
95 |
96 | // lista.removeInicio();
97 |
98 | lista.adiciona(1);
99 | lista.adiciona(2);
100 | lista.adiciona(3);
101 |
102 | System.out.println("Elemento removido: " + lista.removeInicio());
103 | System.out.println("Lista: " + lista);
104 |
105 | System.out.println("Elemento removido: " + lista.removeInicio());
106 | System.out.println("Lista: " + lista);
107 |
108 | System.out.println("Elemento removido: " + lista.removeInicio());
109 | System.out.println("Lista: " + lista);
110 | }
111 |
112 | public static void adicionaPosicao() {
113 | ListaEncadeada lista = new ListaEncadeada<>();
114 | // lista.adiciona(-1, 1);
115 | lista.adiciona(1);
116 | lista.adiciona(2);
117 | lista.adiciona(4); // 1, 2, 4
118 |
119 | // lista.adiciona(5, 0);
120 | lista.adiciona(0, 0); // 0, 1, 2, 4
121 | lista.adiciona(4, 5); // 0, 1, 2, 4, 5
122 | lista.adiciona(2, 3); // 0, 1, 2, 3, 4, 5
123 |
124 | System.out.println(lista);
125 | }
126 |
127 | public static void adicionaInicio() {
128 | ListaEncadeada lista = new ListaEncadeada<>();
129 |
130 | lista.adicionaInicio(3);
131 | lista.adicionaInicio(2);
132 | lista.adicionaInicio(1); // 1, 2, 3
133 |
134 | System.out.println(lista);
135 | }
136 |
137 | public static void testesIniciais() {
138 | ListaEncadeada lista = new ListaEncadeada<>();
139 | lista.adiciona(1);
140 |
141 | System.out.println("Tamanho = " + lista.getTamanho());
142 | System.out.println(lista);
143 |
144 | lista.adiciona(2);
145 | System.out.println(lista);
146 |
147 | lista.adiciona(3);
148 | System.out.println(lista);
149 |
150 | // lista.limpa();
151 | // System.out.println(lista);
152 |
153 | // busca por elemento
154 | System.out.println("******* busca por elemento ");
155 | System.out.println(lista.busca(1));
156 | System.out.println(lista.busca(2));
157 | System.out.println(lista.busca(3));
158 | System.out.println(lista.busca(0));
159 |
160 | // busca por posição
161 | System.out.println("******* busca por posição ");
162 | System.out.println(lista.buscaPorPosicao(0));
163 | System.out.println(lista.buscaPorPosicao(1));
164 | System.out.println(lista.buscaPorPosicao(2));
165 | // System.out.println(lista.buscaPorPosicao(-1));
166 | // System.out.println(lista.buscaPorPosicao(4));
167 | }
168 | }
169 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/pilha/Pilha.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.pilha;
2 |
3 | import com.loiane.estruturadados.base.EstruturaEstatica;
4 |
5 | public class Pilha extends EstruturaEstatica {
6 |
7 | public Pilha(){
8 | super();
9 | }
10 |
11 | public Pilha(int capacidade){
12 | super(capacidade);
13 | }
14 |
15 | public void empilha(T elemento){
16 | super.adiciona(elemento);
17 | }
18 |
19 | public T topo(){
20 |
21 | if (this.estaVazia()){
22 | return null;
23 | }
24 |
25 | return this.elementos[tamanho-1];
26 | }
27 |
28 | public T desempilha(){
29 |
30 | if (this.estaVazia()){
31 | return null;
32 | }
33 |
34 | /*T elemento = this.elementos[tamanho-1];
35 | tamanho--;
36 |
37 | return elemento;*/
38 |
39 | return this.elementos[--tamanho];
40 | }
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/pilha/labs/Exer01.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.pilha.labs;
2 |
3 | import java.util.Scanner;
4 |
5 | import com.loiane.estruturadados.pilha.Pilha;
6 |
7 | public class Exer01 {
8 |
9 | public static void main(String[] args) {
10 |
11 | Pilha pilha = new Pilha();
12 |
13 | Scanner scan = new Scanner(System.in);
14 |
15 | for (int i=1; i<=10; i++){
16 |
17 | System.out.println("Entre com um número:");
18 |
19 | int num = scan.nextInt();
20 |
21 | if (num % 2 == 0){
22 |
23 | System.out.println("Empilhando o número " + num);
24 | pilha.empilha(num);
25 | } else {
26 |
27 | Integer desempilhado = pilha.desempilha();
28 |
29 | if (desempilhado == null){
30 | System.out.println("Pilha está vazia");
31 | } else {
32 | System.out.println("Número ímpar, desempilhando um elemento da pilha: "
33 | + desempilhado);
34 | }
35 | }
36 | }
37 |
38 | System.out.println("Todos os número foram lidos, desempilhando números da pilha");
39 |
40 | while (!pilha.estaVazia()){
41 |
42 | System.out.println("Desempilhando um elemento da pilha: "
43 | + pilha.desempilha());
44 | }
45 |
46 | System.out.println("Todos os elementos foram desempilhados");
47 | }
48 |
49 | }
50 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/pilha/labs/Exer02.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.pilha.labs;
2 |
3 | import java.util.Scanner;
4 |
5 | import com.loiane.estruturadados.pilha.Pilha;
6 |
7 | public class Exer02 {
8 |
9 | public static void main(String[] args) {
10 |
11 | Pilha par = new Pilha();
12 | Pilha impar = new Pilha();
13 |
14 | Scanner scan = new Scanner(System.in);
15 |
16 | for (int i=1; i<=10; i++){
17 |
18 | System.out.println("Entre com um número: ");
19 |
20 | int num = scan.nextInt();
21 |
22 | if (num == 0){
23 |
24 | //pilha par
25 |
26 | Integer desempilhado = par.desempilha();
27 |
28 | if (desempilhado == null){
29 | System.out.println("Pilha par vazia");
30 | } else {
31 | System.out.println("Desempilhando da pilha par: " + desempilhado);
32 | }
33 |
34 | //pilha impar
35 |
36 | desempilhado = impar.desempilha();
37 |
38 | if (desempilhado == null){
39 | System.out.println("Pilha impar vazia");
40 | } else {
41 | System.out.println("Desempilhando da pilha impar: " + desempilhado);
42 | }
43 |
44 |
45 | } else if (num % 2 == 0){
46 | System.out.println("Número par, empilhando na pilha par: " + num);
47 | par.empilha(num);
48 | } else {
49 | System.out.println("Número ímpar, empilhando na pilha ímpar: " + num);
50 | impar.empilha(num);
51 | }
52 | }
53 |
54 | System.out.println("Desempilhando todos os números da pilhar par");
55 |
56 | while (!par.estaVazia()){
57 | System.out.println("Desempilhando da pilha par: " + par.desempilha());
58 | }
59 |
60 | System.out.println("Desempilhando todos os números da pilhar ímpar");
61 |
62 | while (!impar.estaVazia()){
63 | System.out.println("Desempilhando da pilha impar: " + impar.desempilha());
64 | }
65 |
66 | }
67 |
68 | }
69 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/pilha/labs/Exer03.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.pilha.labs;
2 |
3 | import com.loiane.estruturadados.pilha.Pilha;
4 |
5 | public class Exer03 {
6 |
7 | public static void main(String[] args) {
8 |
9 | Pilha pilha = new Pilha(20);
10 |
11 | Livro livro1 = new Livro();
12 | livro1.setNome("Learning JavaScript Data Structures and Algorithms - Second Edition");
13 | livro1.setAutor("Loiane Groner");
14 | livro1.setAnoLancamento(2016);
15 | livro1.setIsbn("B01C2XX8Y2");
16 |
17 | Livro livro2 = new Livro();
18 | livro2.setNome("Learning JavaScript Data Structures and Algorithms");
19 | livro2.setAutor("Loiane Groner");
20 | livro2.setAnoLancamento(2014);
21 | livro2.setIsbn("B00OYTCT02");
22 |
23 | Livro livro3 = new Livro();
24 | livro3.setNome("Mastering Ext JS - Second Edition");
25 | livro3.setAutor("Loiane Groner");
26 | livro3.setAnoLancamento(2015);
27 | livro3.setIsbn("B00U01QQWU");
28 |
29 | Livro livro4 = new Livro();
30 | livro4.setNome("JavaScript Regular Expressions");
31 | livro4.setAutor("Loiane Groner");
32 | livro4.setAnoLancamento(2015);
33 | livro4.setIsbn("B00YHBVHGO");
34 |
35 | System.out.println("Pilha de livros criada, pilha está vazia? "+ pilha.estaVazia());
36 |
37 | System.out.println("Empilhando livros na pilha:");
38 |
39 | pilha.empilha(livro1);
40 | pilha.empilha(livro2);
41 | pilha.empilha(livro3);
42 | pilha.empilha(livro4);
43 |
44 | System.out.println(pilha.tamanho() + " livros foram empilhados:");
45 | System.out.println(pilha);
46 |
47 | System.out.println("Pilha de livros criada, pilha está vazia? "+ pilha.estaVazia());
48 |
49 | System.out.println("Espiando o topo da pilha: " + pilha.topo());
50 |
51 | System.out.println("Desempilhando livros da pilha:");
52 |
53 | while (!pilha.estaVazia()){
54 | System.out.println("Desempilhando livro: " + pilha.desempilha());
55 | }
56 |
57 | System.out.println("Todos os livros foram desempilhandos, pilha vazia: " + pilha.estaVazia());
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/pilha/labs/Exer04.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.pilha.labs;
2 |
3 | import java.util.Stack;
4 |
5 | public class Exer04 {
6 |
7 | public static void main(String[] args) {
8 |
9 | Stack pilha = new Stack();
10 |
11 | Livro livro1 = new Livro();
12 | livro1.setNome("Learning JavaScript Data Structures and Algorithms - Second Edition");
13 | livro1.setAutor("Loiane Groner");
14 | livro1.setAnoLancamento(2016);
15 | livro1.setIsbn("B01C2XX8Y2");
16 |
17 | Livro livro2 = new Livro();
18 | livro2.setNome("Learning JavaScript Data Structures and Algorithms");
19 | livro2.setAutor("Loiane Groner");
20 | livro2.setAnoLancamento(2014);
21 | livro2.setIsbn("B00OYTCT02");
22 |
23 | Livro livro3 = new Livro();
24 | livro3.setNome("Mastering Ext JS - Second Edition");
25 | livro3.setAutor("Loiane Groner");
26 | livro3.setAnoLancamento(2015);
27 | livro3.setIsbn("B00U01QQWU");
28 |
29 | Livro livro4 = new Livro();
30 | livro4.setNome("JavaScript Regular Expressions");
31 | livro4.setAutor("Loiane Groner");
32 | livro4.setAnoLancamento(2015);
33 | livro4.setIsbn("B00YHBVHGO");
34 |
35 | System.out.println("Pilha de livros criada, pilha está vazia? "+ pilha.isEmpty());
36 |
37 | System.out.println("Empilhando livros na pilha:");
38 |
39 | pilha.push(livro1);
40 | pilha.push(livro2);
41 | pilha.push(livro3);
42 | pilha.push(livro4);
43 |
44 | System.out.println(pilha.size() + " livros foram empilhados:");
45 | System.out.println(pilha);
46 |
47 | System.out.println("Pilha de livros criada, pilha está vazia? "+ pilha.isEmpty());
48 |
49 | System.out.println("Espiando o topo da pilha: " + pilha.peek());
50 |
51 | System.out.println("Desempilhando livros da pilha:");
52 |
53 | while (!pilha.isEmpty()){
54 | System.out.println("Desempilhando livro: " + pilha.pop());
55 | }
56 |
57 | System.out.println("Todos os livros foram desempilhandos, pilha vazia: " + pilha.isEmpty());
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/pilha/labs/Exer05.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.pilha.labs;
2 |
3 | import com.loiane.estruturadados.pilha.Pilha;
4 |
5 | public class Exer05 {
6 |
7 | public static void main(String[] args) {
8 |
9 | imprimeResultado("ADA");
10 |
11 | imprimeResultado("ABCD");
12 |
13 | imprimeResultado("ABCCBA");
14 |
15 | imprimeResultado("Maria");
16 | }
17 |
18 | public static void imprimeResultado(String palavra){
19 | System.out.println(palavra + " é palindromo? " + testaPalindromo(palavra));
20 | }
21 |
22 | public static boolean testaPalindromo(String palavra){
23 |
24 | Pilha pilha = new Pilha();
25 |
26 | for (int i=0; i pilha = new Pilha();
27 | int index = 0;
28 | char simbolo, topo;
29 |
30 | while (index < expressao.length()){
31 | simbolo = expressao.charAt(index);
32 |
33 | if (ABRE.indexOf(simbolo) > -1){
34 | pilha.empilha(simbolo);
35 |
36 | } else if (FECHA.indexOf(simbolo) > -1){
37 |
38 | if (pilha.estaVazia()){
39 | return false;
40 | } else {
41 | topo = pilha.desempilha();
42 |
43 | if (ABRE.indexOf(topo) != FECHA.indexOf(simbolo)){
44 | return false;
45 | }
46 | }
47 | }
48 |
49 | index++;
50 | }
51 |
52 | return pilha.estaVazia();
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/pilha/labs/Exer07.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.pilha.labs;
2 |
3 | import java.util.Stack;
4 |
5 | public class Exer07 {
6 |
7 | public static void main(String[] args) {
8 |
9 | imprimeResultado(2);
10 |
11 | imprimeResultado(4);
12 |
13 | imprimeResultado(10);
14 |
15 | imprimeResultado(25);
16 |
17 | imprimeResultado(10035);
18 |
19 | imprimeResultadoQualquerBase(25, 16);
20 |
21 | imprimeResultadoQualquerBase(10035, 8);
22 |
23 | imprimeResultadoQualquerBase(10035, 16);
24 |
25 | }
26 |
27 | public static void imprimeResultado(int numero){
28 | System.out.println(numero + " em binário é: " + decimalBinario(numero));
29 | }
30 |
31 | public static void imprimeResultadoQualquerBase(int numero, int base){
32 | System.out.println(numero + " na base " + base +
33 | " é: " + decimalQualquerBase(numero, base));
34 | }
35 |
36 | public static String decimalBinario(int numero){
37 |
38 | Stack pilha = new Stack<>();
39 | String numBinario = "";
40 | int resto;
41 |
42 | while (numero > 0){
43 | resto = numero % 2;
44 | pilha.push(resto);
45 | numero /= 2; //numero = numero /2
46 | }
47 |
48 | while (!pilha.isEmpty()){
49 | numBinario += pilha.pop();
50 | }
51 |
52 | return numBinario;
53 | }
54 |
55 | public static String decimalQualquerBase(int numero, int base){
56 |
57 | if (base > 16){
58 | throw new IllegalArgumentException();
59 | }
60 |
61 | Stack pilha = new Stack<>();
62 | String numBase = "";
63 | int resto;
64 | String bases = "0123456789ABCDEF";
65 |
66 | while (numero > 0){
67 | resto = numero % base;
68 | pilha.push(resto);
69 | numero /= base;
70 | }
71 |
72 | while (!pilha.isEmpty()){
73 | numBase += bases.charAt(pilha.pop());
74 | }
75 |
76 | return numBase;
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/pilha/labs/Exer08.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.pilha.labs;
2 |
3 | import java.util.Stack;
4 |
5 | public class Exer08 {
6 |
7 | public static void main(String[] args) {
8 |
9 | Stack original = new Stack<>();
10 | Stack dest = new Stack<>();
11 | Stack aux = new Stack<>();
12 |
13 | original.push(3);
14 | original.push(2);
15 | original.push(1);
16 |
17 | torreDeHanoi(original.size(), original, dest, aux);
18 | }
19 |
20 | public static void torreDeHanoi(int n, Stack original,
21 | Stack dest, Stack aux){
22 |
23 | if (n > 0){
24 | torreDeHanoi(n-1, original, aux, dest);
25 | dest.push(original.pop());
26 | System.out.println("------");
27 | System.out.println("Original: " + original);
28 | System.out.println("Destino: " + dest);
29 | System.out.println("Aux: " + aux);
30 | torreDeHanoi(n-1, aux, dest, original);
31 | }
32 |
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/pilha/labs/Livro.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.pilha.labs;
2 |
3 | public class Livro {
4 |
5 | private String isbn;
6 | private String autor;
7 | private int anoLancamento;
8 | private String nome;
9 |
10 | public Livro() {
11 | super();
12 | }
13 | public Livro(String isbn, String autor, int anoLancamento, String nome) {
14 | super();
15 | this.isbn = isbn;
16 | this.autor = autor;
17 | this.anoLancamento = anoLancamento;
18 | this.nome = nome;
19 | }
20 | public String getIsbn() {
21 | return isbn;
22 | }
23 | public void setIsbn(String isbn) {
24 | this.isbn = isbn;
25 | }
26 | public String getAutor() {
27 | return autor;
28 | }
29 | public void setAutor(String autor) {
30 | this.autor = autor;
31 | }
32 | public int getAnoLancamento() {
33 | return anoLancamento;
34 | }
35 | public void setAnoLancamento(int anoLancamento) {
36 | this.anoLancamento = anoLancamento;
37 | }
38 | public String getNome() {
39 | return nome;
40 | }
41 | public void setNome(String nome) {
42 | this.nome = nome;
43 | }
44 | @Override
45 | public String toString() {
46 | return "Livro [isbn=" + isbn + ", autor=" + autor + ", anoLancamento="
47 | + anoLancamento + ", nome=" + nome + "]";
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/pilha/teste/Aula13.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.pilha.teste;
2 |
3 | import com.loiane.estruturadados.pilha.Pilha;
4 |
5 | public class Aula13 {
6 |
7 | public static void main(String[] args) {
8 |
9 | Pilha pilha = new Pilha();
10 |
11 | System.out.println(pilha);
12 | System.out.println(pilha.tamanho());
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/pilha/teste/Aula14.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.pilha.teste;
2 |
3 | import com.loiane.estruturadados.pilha.Pilha;
4 |
5 | public class Aula14 {
6 |
7 | public static void main(String[] args) {
8 |
9 | Pilha pilha = new Pilha();
10 |
11 | for (int i=1; i<=11; i++){
12 | pilha.empilha(i);
13 | }
14 |
15 | System.out.println(pilha);
16 | System.out.println(pilha.tamanho());
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/pilha/teste/Aula15.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.pilha.teste;
2 |
3 | import com.loiane.estruturadados.pilha.Pilha;
4 |
5 | public class Aula15 {
6 |
7 | public static void main(String[] args) {
8 |
9 | Pilha pilha = new Pilha();
10 |
11 | System.out.println(pilha.estaVazia());
12 |
13 | pilha.empilha(1);
14 |
15 | System.out.println(pilha.estaVazia());
16 |
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/pilha/teste/Aula16.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.pilha.teste;
2 |
3 | import com.loiane.estruturadados.pilha.Pilha;
4 |
5 | public class Aula16 {
6 |
7 | public static void main(String[] args) {
8 |
9 | Pilha pilha = new Pilha();
10 |
11 | System.out.println(pilha.topo());
12 |
13 | System.out.println(pilha);
14 |
15 | pilha.empilha(1);
16 | pilha.empilha(2);
17 |
18 | System.out.println(pilha.topo());
19 |
20 | System.out.println(pilha);
21 | }
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/pilha/teste/Aula17.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.pilha.teste;
2 |
3 | import com.loiane.estruturadados.pilha.Pilha;
4 |
5 | public class Aula17 {
6 |
7 | public static void main(String[] args) {
8 |
9 | Pilha pilha = new Pilha();
10 |
11 | pilha.empilha(1);
12 | pilha.empilha(2);
13 | pilha.empilha(3);
14 |
15 | System.out.println(pilha);
16 |
17 | System.out.println("Desempilhando elemento " + pilha.desempilha());
18 |
19 | System.out.println(pilha);
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/pilha/teste/Aula18.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.pilha.teste;
2 |
3 | import java.util.Stack;
4 |
5 | import com.loiane.estruturadados.pilha.Pilha;
6 |
7 | public class Aula18 {
8 |
9 | public static void main(String[] args) {
10 |
11 | Pilha pilha = new Pilha();
12 |
13 | Stack stack = new Stack();
14 |
15 | System.out.println(stack.isEmpty());
16 |
17 | stack.push(1);
18 | stack.push(2);
19 | stack.push(3);
20 |
21 | System.out.println(stack.isEmpty());
22 | System.out.println(stack.size());
23 | System.out.println(stack);
24 |
25 | System.out.println(stack.peek());
26 |
27 | System.out.println(stack.pop());
28 |
29 | System.out.println(stack);
30 | }
31 |
32 | }
33 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/vetor/Lista.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.vetor;
2 |
3 | import java.lang.reflect.Array;
4 |
5 | public class Lista {
6 |
7 | private T[] elementos;
8 | private int tamanho;
9 |
10 | public Lista(int capacidade){
11 | this.elementos = (T[]) new Object[capacidade]; //solução do livro effective Java
12 | this.tamanho = 0;
13 | }
14 |
15 | public Lista(){
16 | this(10);
17 | }
18 |
19 | public Lista(int capacidade, Class tipoClasse){
20 | this.elementos = (T[]) Array.newInstance(tipoClasse, capacidade);
21 | this.tamanho = 0;
22 | }
23 |
24 | public boolean adiciona(T elemento) {
25 | this.aumentaCapacidade();
26 | if (this.tamanho < this.elementos.length){
27 | this.elementos[this.tamanho] = elemento;
28 | this.tamanho++;
29 | return true;
30 | }
31 | return false;
32 | }
33 |
34 | // 0 1 2 3 4 5 6 = tamanho é 5
35 | // B C E F G + +
36 | //
37 | public boolean adiciona(int posicao, T elemento){
38 |
39 | if (!(posicao >= 0 && posicao < tamanho)){
40 | throw new IllegalArgumentException("Posição inválida");
41 | }
42 |
43 | this.aumentaCapacidade();
44 |
45 | //mover todos os elementos
46 | for (int i=this.tamanho-1; i>=posicao; i--){
47 | this.elementos[i+1] = this.elementos[i];
48 | }
49 | this.elementos[posicao] = elemento;
50 | this.tamanho++;
51 |
52 | return true;
53 | }
54 |
55 | private void aumentaCapacidade(){
56 | if (this.tamanho == this.elementos.length){
57 | T[] elementosNovos = (T[]) new Object[this.elementos.length * 2];
58 | for (int i=0; i= 0 && posicao < tamanho)){
71 | throw new IllegalArgumentException("Posição inválida");
72 | }
73 | return this.elementos[posicao];
74 | }
75 |
76 | public int busca(T elemento){
77 | for (int i=0; i=0; i--){
88 | if (this.elementos[i].equals(elemento)){
89 | return i;
90 | }
91 | }
92 | return -1;
93 | }
94 |
95 | public boolean contem(T elemento){
96 |
97 | /*int pos = busca(elemento);
98 | if (pos > -1){
99 | return true;
100 | }
101 |
102 | return false;*/
103 |
104 | return busca(elemento) > -1; //>=0
105 | }
106 |
107 | // B D E F F -> posição a ser removida é 1 (G)
108 | // 0 1 2 3 4 -> tamanho é 5
109 | // vetor[1] = vetor[2]
110 | // vetor[2] = vetor[3]
111 | // vetor[3] = vetor[4]
112 | public void remove(int posicao){
113 | if (!(posicao >= 0 && posicao < tamanho)){
114 | throw new IllegalArgumentException("Posição inválida");
115 | }
116 | for (int i=posicao; i -1){
125 | this.remove(pos);
126 | }
127 | }
128 |
129 | public void limpar(){
130 | //opção 1
131 | //this.elementos = (T[]) new Object[this.elementos.length];
132 |
133 | //opção 2
134 | //this.tamanho = 0;
135 |
136 | //opção 3
137 | for (int i=0; i0){
159 | s.append(this.elementos[this.tamanho-1]);
160 | }
161 |
162 | s.append("]");
163 |
164 | return s.toString();
165 | }
166 | }
167 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/vetor/Lista2.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.vetor;
2 |
3 | import com.loiane.estruturadados.base.EstruturaEstatica;
4 |
5 | public class Lista2 extends EstruturaEstatica {
6 |
7 | public Lista2(int capacidade) {
8 | super(capacidade);
9 | }
10 |
11 | public Lista2() {
12 | super();
13 | }
14 |
15 | public boolean adiciona(T elemento) {
16 | return super.adiciona(elemento);
17 | }
18 |
19 | public boolean adiciona(int posicao, T elemento){
20 | return super.adiciona(posicao, elemento);
21 | }
22 |
23 | public void remove(int posicao){
24 | super.remove(posicao);
25 | }
26 |
27 | public T busca(int posicao){
28 | if (!(posicao >= 0 && posicao < tamanho)){
29 | throw new IllegalArgumentException("Posicao inválida");
30 | }
31 | return elementos[posicao];
32 | }
33 |
34 | public int busca(T elemento){
35 | for (int i=0; i= 0 && posicao < tamanho)){
49 | throw new IllegalArgumentException("Posição inválida");
50 | }
51 |
52 | this.aumentaCapacidade();
53 |
54 | //mover todos os elementos
55 | for (int i=this.tamanho-1; i>=posicao; i--){
56 | this.elementos[i+1] = this.elementos[i];
57 | }
58 | this.elementos[posicao] = elemento;
59 | this.tamanho++;
60 |
61 | return true;
62 | }
63 |
64 | private void aumentaCapacidade(){
65 | if (this.tamanho == this.elementos.length){
66 | String[] elementosNovos = new String[this.elementos.length * 2];
67 | for (int i=0; i= 0 && posicao < tamanho)){
76 | throw new IllegalArgumentException("Posição inválida");
77 | }
78 | return this.elementos[posicao];
79 | }
80 |
81 | public int busca(String elemento){
82 | for (int i=0; i posição a ser removida é 1 (G)
91 | // 0 1 2 3 4 -> tamanho é 5
92 | // vetor[1] = vetor[2]
93 | // vetor[2] = vetor[3]
94 | // vetor[3] = vetor[4]
95 | public void remove(int posicao){
96 | if (!(posicao >= 0 && posicao < tamanho)){
97 | throw new IllegalArgumentException("Posição inválida");
98 | }
99 | for (int i=posicao; i0){
121 | s.append(this.elementos[this.tamanho-1]);
122 | }
123 |
124 | s.append("]");
125 |
126 | return s.toString();
127 | }
128 |
129 | }
130 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/vetor/VetorObjetos.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.vetor;
2 |
3 | public class VetorObjetos {
4 |
5 | private Object[] elementos;
6 | private int tamanho;
7 |
8 | public VetorObjetos(int capacidade){
9 | this.elementos = new Object[capacidade];
10 | this.tamanho = 0;
11 | }
12 |
13 | public boolean adiciona(Object elemento) {
14 | this.aumentaCapacidade();
15 | if (this.tamanho < this.elementos.length){
16 | this.elementos[this.tamanho] = elemento;
17 | this.tamanho++;
18 | return true;
19 | }
20 | return false;
21 | }
22 |
23 | // 0 1 2 3 4 5 6 = tamanho é 5
24 | // B C E F G + +
25 | //
26 | public boolean adiciona(int posicao, Object elemento){
27 |
28 | if (!(posicao >= 0 && posicao < tamanho)){
29 | throw new IllegalArgumentException("Posição inválida");
30 | }
31 |
32 | this.aumentaCapacidade();
33 |
34 | //mover todos os elementos
35 | for (int i=this.tamanho-1; i>=posicao; i--){
36 | this.elementos[i+1] = this.elementos[i];
37 | }
38 | this.elementos[posicao] = elemento;
39 | this.tamanho++;
40 |
41 | return true;
42 | }
43 |
44 | private void aumentaCapacidade(){
45 | if (this.tamanho == this.elementos.length){
46 | Object[] elementosNovos = new Object[this.elementos.length * 2];
47 | for (int i=0; i= 0 && posicao < tamanho)){
56 | throw new IllegalArgumentException("Posição inválida");
57 | }
58 | return this.elementos[posicao];
59 | }
60 |
61 | public int busca(Object elemento){
62 | for (int i=0; i posição a ser removida é 1 (G)
71 | // 0 1 2 3 4 -> tamanho é 5
72 | // vetor[1] = vetor[2]
73 | // vetor[2] = vetor[3]
74 | // vetor[3] = vetor[4]
75 | public void remove(int posicao){
76 | if (!(posicao >= 0 && posicao < tamanho)){
77 | throw new IllegalArgumentException("Posição inválida");
78 | }
79 | for (int i=posicao; i0){
101 | s.append(this.elementos[this.tamanho-1]);
102 | }
103 |
104 | s.append("]");
105 |
106 | return s.toString();
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/vetor/labs/Exer01.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.vetor.labs;
2 |
3 | import com.loiane.estruturadados.vetor.Lista;
4 |
5 | public class Exer01 {
6 |
7 | public static void main(String[] args) {
8 |
9 | Lista lista = new Lista(5);
10 |
11 | lista.adiciona("A");
12 | lista.adiciona("B");
13 | lista.adiciona("C");
14 |
15 | System.out.println(lista.contem("A"));
16 | System.out.println(lista.contem("B"));
17 | System.out.println(lista.contem("E"));
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/vetor/labs/Exer02.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.vetor.labs;
2 |
3 | import java.util.ArrayList;
4 |
5 | import com.loiane.estruturadados.vetor.Lista;
6 |
7 | public class Exer02 {
8 |
9 | public static void main(String[] args) {
10 |
11 | ArrayList arrayList = new ArrayList(5);
12 | arrayList.add("A");
13 | arrayList.add("B");
14 | arrayList.add("A");
15 |
16 | System.out.println(arrayList.lastIndexOf("A"));
17 |
18 | Lista lista = new Lista(5);
19 | lista.adiciona("A");
20 | lista.adiciona("B");
21 | lista.adiciona("A");
22 |
23 | System.out.println(lista.ultimoIndice("A"));
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/vetor/labs/Exer03.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.vetor.labs;
2 |
3 | import com.loiane.estruturadados.vetor.Lista;
4 |
5 | public class Exer03 {
6 |
7 | public static void main(String[] args) {
8 |
9 | Lista lista = new Lista(5);
10 |
11 | lista.adiciona("A");
12 | lista.adiciona("B");
13 | lista.adiciona("C");
14 | lista.adiciona("D");
15 | lista.adiciona("E");
16 |
17 | System.out.println(lista);
18 |
19 | lista.remove("A");
20 |
21 | System.out.println(lista);
22 |
23 | lista.remove("E");
24 |
25 | System.out.println(lista);
26 |
27 | lista.remove("C");
28 |
29 | System.out.println(lista);
30 |
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/vetor/labs/Exer04.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.vetor.labs;
2 |
3 | import com.loiane.estruturadados.vetor.Lista;
4 |
5 | public class Exer04 {
6 |
7 | public static void main(String[] args) {
8 |
9 | Lista lista = new Lista(5);
10 |
11 | lista.adiciona("A");
12 | lista.adiciona("B");
13 | lista.adiciona("C");
14 | lista.adiciona("D");
15 | lista.adiciona("E");
16 |
17 | System.out.println(lista.obtem(0));
18 | System.out.println(lista.obtem(2));
19 | System.out.println(lista.obtem(4));
20 | }
21 |
22 | }
23 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/vetor/labs/Exer05.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.vetor.labs;
2 |
3 | import java.util.ArrayList;
4 |
5 | import com.loiane.estruturadados.vetor.Lista;
6 |
7 | public class Exer05 {
8 |
9 | public static void main(String[] args) {
10 |
11 | ArrayList arrayList = new ArrayList(5);
12 |
13 | arrayList.add("A");
14 | arrayList.add("B");
15 | arrayList.add("C");
16 | arrayList.add("D");
17 | arrayList.add("E");
18 |
19 | System.out.println(arrayList);
20 |
21 | arrayList.clear();
22 |
23 | System.out.println(arrayList);
24 |
25 |
26 | Lista lista = new Lista(5);
27 |
28 | lista.adiciona("A");
29 | lista.adiciona("B");
30 | lista.adiciona("C");
31 | lista.adiciona("D");
32 | lista.adiciona("E");
33 |
34 | System.out.println(lista);
35 |
36 | lista.limpar();
37 |
38 | System.out.println(lista);
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/vetor/labs/Exer06.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.vetor.labs;
2 |
3 | import java.util.Scanner;
4 |
5 | import com.loiane.estruturadados.vetor.Lista;
6 | import com.loiane.estruturadados.vetor.teste.Contato;
7 |
8 | public class Exer06 {
9 |
10 | public static void main(String[] args) {
11 |
12 | //criação das variáveis
13 | Scanner scan = new Scanner(System.in);
14 |
15 | //criar vetor com 20 de capacidade
16 | Lista lista = new Lista(20);
17 |
18 | //criar e adicionar X contatos
19 | criarContatosDinamicamente(5, lista);
20 |
21 | //criar um menu para que o usuário escolha a opção
22 | int opcao = 1;
23 |
24 | while (opcao != 0){
25 |
26 | opcao = obterOpcaoMenu(scan);
27 |
28 | switch (opcao) {
29 | case 1:
30 | adicionarContatoFinal(scan, lista);
31 | break;
32 | case 2:
33 | adicionarContatoPosicao(scan, lista);
34 | break;
35 | case 3:
36 | obtemContatoPosicao(scan, lista);
37 | break;
38 | case 4:
39 | obtemContato(scan, lista);
40 | break;
41 | case 5:
42 | pesquisarUltimoIndice(scan, lista);
43 | break;
44 | case 6:
45 | pesquisarContatoExiste(scan, lista);
46 | break;
47 | case 7:
48 | excluirPorPosicao(scan, lista);
49 | break;
50 | case 8:
51 | excluirContato(scan, lista);
52 | break;
53 | case 9:
54 | imprimeTamanhoVetor(lista);
55 | break;
56 | case 10:
57 | limparVetor(lista);
58 | break;
59 | case 11:
60 | imprimirVetor(lista);
61 | break;
62 | default:
63 | break;
64 | }
65 | }
66 |
67 | System.out.println("Usuário digitou 0, programa terminado");
68 | }
69 |
70 | private static void imprimirVetor(Lista lista){
71 |
72 | System.out.println(lista);
73 | }
74 |
75 | private static void limparVetor(Lista lista){
76 |
77 | lista.limpar();
78 |
79 | System.out.println("Todos os contatos do vetor foram excluídos");
80 | }
81 |
82 | private static void imprimeTamanhoVetor(Lista lista){
83 |
84 | System.out.println("Tamanho do vetor é de: " + lista.tamanho());
85 | }
86 |
87 | private static void excluirPorPosicao(Scanner scan, Lista lista){
88 |
89 | int pos = leInformacaoInt("Entre com a posição a ser removida", scan);
90 |
91 | try {
92 |
93 | lista.remove(pos);
94 |
95 | System.out.println("Contato excluído");
96 |
97 | } catch (Exception e) {
98 | System.out.println("Posição inválida!");
99 | }
100 | }
101 |
102 | private static void excluirContato(Scanner scan, Lista lista){
103 |
104 | int pos = leInformacaoInt("Entre com a posição a ser removida", scan);
105 |
106 | try {
107 |
108 | Contato contato = lista.busca(pos);
109 |
110 | lista.remove(contato);
111 |
112 | System.out.println("Contato excluído");
113 |
114 | } catch (Exception e) {
115 | System.out.println("Posição inválida!");
116 | }
117 | }
118 |
119 | private static void pesquisarContatoExiste(Scanner scan, Lista lista){
120 |
121 | int pos = leInformacaoInt("Entre com a posição a ser pesquisada", scan);
122 |
123 | try {
124 |
125 | Contato contato = lista.busca(pos);
126 |
127 | boolean existe = lista.contem(contato);
128 |
129 | if (existe){
130 | System.out.println("Contato existe, seguem dados:");
131 | System.out.println(contato);
132 | } else {
133 | System.out.println("Contato não existe");
134 | }
135 |
136 | } catch (Exception e) {
137 | System.out.println("Posição inválida!");
138 | }
139 | }
140 |
141 | private static void pesquisarUltimoIndice(Scanner scan, Lista lista){
142 |
143 | int pos = leInformacaoInt("Entre com a posição a ser pesquisada", scan);
144 |
145 | try {
146 |
147 | Contato contato = lista.busca(pos);
148 |
149 | System.out.println("Contato existe, seguem dados:");
150 | System.out.println(contato);
151 |
152 | System.out.println("Fazendo pesquisa do último índice do contato encontrado:");
153 | pos = lista.ultimoIndice(contato);
154 |
155 | System.out.println("Contato encontrado na posição " + pos);
156 |
157 | } catch (Exception e) {
158 | System.out.println("Posição inválida!");
159 | }
160 | }
161 |
162 | private static void obtemContato(Scanner scan, Lista lista){
163 |
164 | int pos = leInformacaoInt("Entre com a posição a ser pesquisada", scan);
165 |
166 | try {
167 |
168 | Contato contato = lista.busca(pos);
169 |
170 | System.out.println("Contato existe, seguem dados:");
171 | System.out.println(contato);
172 |
173 | System.out.println("Fazendo pesquisa do contato encontrado:");
174 | pos = lista.busca(contato);
175 |
176 | System.out.println("Contato encontrado na posição " + pos);
177 |
178 | } catch (Exception e) {
179 | System.out.println("Posição inválida!");
180 | }
181 | }
182 |
183 | private static void obtemContatoPosicao(Scanner scan, Lista lista){
184 |
185 | int pos = leInformacaoInt("Entre com a posição a ser pesquisada", scan);
186 |
187 | try {
188 |
189 | Contato contato = lista.busca(pos);
190 |
191 | System.out.println("Contato existe, seguem dados:");
192 | System.out.println(contato);
193 |
194 | } catch (Exception e) {
195 | System.out.println("Posição inválida!");
196 | }
197 | }
198 |
199 | private static void adicionarContatoFinal(Scanner scan, Lista lista){
200 |
201 | System.out.println("Criando um contato, entre com as informações:");
202 | String nome = leInformacao("Entre com o nome", scan);
203 | String telefone = leInformacao("Entre com o telefone", scan);
204 | String email = leInformacao("Entre com o email", scan);
205 |
206 | Contato contato = new Contato(nome, telefone, email);
207 |
208 | lista.adiciona(contato);
209 |
210 | System.out.println("Contato adicionado com sucesso!");
211 | System.out.println(contato);
212 | }
213 |
214 | private static void adicionarContatoPosicao(Scanner scan, Lista lista){
215 |
216 | System.out.println("Criando um contato, entre com as informações:");
217 | String nome = leInformacao("Entre com o nome", scan);
218 | String telefone = leInformacao("Entre com o telefone", scan);
219 | String email = leInformacao("Entre com o email", scan);
220 |
221 | Contato contato = new Contato(nome, telefone, email);
222 |
223 | int pos = leInformacaoInt("Entre com a posição a adicionar o contato", scan);
224 |
225 | try {
226 | lista.adiciona(pos, contato);
227 |
228 | System.out.println("Contato adicionado com sucesso!");
229 | System.out.println(contato);
230 |
231 | } catch (Exception e){
232 | System.out.println("Posição inválida, contato não adicionado");
233 | }
234 | }
235 |
236 | protected static String leInformacao(String msg, Scanner scan){
237 |
238 | System.out.println(msg);
239 | String entrada = scan.nextLine();
240 |
241 | return entrada;
242 | }
243 |
244 | protected static int leInformacaoInt(String msg, Scanner scan){
245 |
246 | boolean entradaValida = false;
247 | int num = 0;
248 |
249 | while (!entradaValida){
250 |
251 | try {
252 |
253 | System.out.println(msg);
254 | String entrada = scan.nextLine();
255 |
256 | num = Integer.parseInt(entrada);
257 |
258 | entradaValida = true;
259 |
260 | } catch (Exception e){
261 | System.out.println("Entrada inválida, digite novamente");
262 | }
263 | }
264 |
265 | return num;
266 | }
267 |
268 | protected static int obterOpcaoMenu(Scanner scan){
269 |
270 | boolean entradaValida = false;
271 | int opcao = 0;
272 | String entrada;
273 |
274 | while (!entradaValida){
275 |
276 | System.out.println("Digite a opção desejada:");
277 | System.out.println("1: Adiciona contato no final do vetor");
278 | System.out.println("2: Adiciona contato em uma posição específica");
279 | System.out.println("3: Obtém contato de uma posição específica");
280 | System.out.println("4: Consulta contato");
281 | System.out.println("5: Consulta último índide do contato");
282 | System.out.println("6: Verifica se contato existe");
283 | System.out.println("7: Excluir por posição");
284 | System.out.println("8: Excluir contato");
285 | System.out.println("9: Verifica tamanho do vetor");
286 | System.out.println("10: Excluir todos os contatos do vetor");
287 | System.out.println("11: Imprime vetor");
288 | System.out.println("0: Sair");
289 |
290 | try {
291 |
292 | entrada = scan.nextLine();
293 | opcao = Integer.parseInt(entrada);
294 |
295 | if (opcao >= 0 && opcao <= 11){
296 | entradaValida = true;
297 | } else {
298 | throw new Exception();
299 | }
300 |
301 | } catch (Exception e){
302 |
303 | System.out.println("Entrada inválida, digite novamente\n\n");
304 | }
305 | }
306 |
307 | return opcao;
308 | }
309 |
310 | protected static void criarContatosDinamicamente(int quantidade, Lista lista){
311 |
312 | Contato contato;
313 |
314 | for (int i=1; i<=quantidade; i++){
315 |
316 | contato = new Contato();
317 | contato.setNome("Contato " + i);
318 | contato.setTelefone("1111111"+i);
319 | contato.setEmail("contato"+i+"@email.com");
320 |
321 | lista.adiciona(contato);
322 | }
323 | }
324 | }
325 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/vetor/labs/Exer07.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.vetor.labs;
2 |
3 | import java.util.ArrayList;
4 | import java.util.Scanner;
5 |
6 | import com.loiane.estruturadados.vetor.teste.Contato;
7 |
8 | public class Exer07 extends Exer06 {
9 |
10 | public static void main(String[] args) {
11 |
12 | //criação das variáveis
13 | Scanner scan = new Scanner(System.in);
14 |
15 | //criar vetor com 20 de capacidade
16 | ArrayList lista = new ArrayList(20);
17 |
18 | //criar e adicionar X contatos
19 | criarContatosDinamicamente(5, lista);
20 |
21 | //criar um menu para que o usuário escolha a opção
22 | int opcao = 1;
23 |
24 | while (opcao != 0){
25 |
26 | opcao = obterOpcaoMenu(scan);
27 |
28 | switch (opcao) {
29 | case 1:
30 | adicionarContatoFinal(scan, lista);
31 | break;
32 | case 2:
33 | adicionarContatoPosicao(scan, lista);
34 | break;
35 | case 3:
36 | obtemContatoPosicao(scan, lista);
37 | break;
38 | case 4:
39 | obtemContato(scan, lista);
40 | break;
41 | case 5:
42 | pesquisarUltimoIndice(scan, lista);
43 | break;
44 | case 6:
45 | pesquisarContatoExiste(scan, lista);
46 | break;
47 | case 7:
48 | excluirPorPosicao(scan, lista);
49 | break;
50 | case 8:
51 | excluirContato(scan, lista);
52 | break;
53 | case 9:
54 | imprimeTamanhoVetor(lista);
55 | break;
56 | case 10:
57 | limparVetor(lista);
58 | break;
59 | case 11:
60 | imprimirVetor(lista);
61 | break;
62 | default:
63 | break;
64 | }
65 | }
66 |
67 | System.out.println("Usuário digitou 0, programa terminado");
68 | }
69 |
70 | private static void imprimirVetor(ArrayList lista){
71 |
72 | System.out.println(lista);
73 | }
74 |
75 | private static void limparVetor(ArrayList lista){
76 |
77 | lista.clear();
78 |
79 | System.out.println("Todos os contatos do vetor foram excluídos");
80 | }
81 |
82 | private static void imprimeTamanhoVetor(ArrayList lista){
83 |
84 | System.out.println("Tamanho do vetor é de: " + lista.size());
85 | }
86 |
87 | private static void excluirPorPosicao(Scanner scan, ArrayList lista){
88 |
89 | int pos = leInformacaoInt("Entre com a posição a ser removida", scan);
90 |
91 | try {
92 |
93 | lista.remove(pos);
94 |
95 | System.out.println("Contato excluído");
96 |
97 | } catch (Exception e) {
98 | System.out.println("Posição inválida!");
99 | }
100 | }
101 |
102 | private static void excluirContato(Scanner scan, ArrayList lista){
103 |
104 | int pos = leInformacaoInt("Entre com a posição a ser removida", scan);
105 |
106 | try {
107 |
108 | Contato contato = lista.get(pos);
109 |
110 | lista.remove(contato);
111 |
112 | System.out.println("Contato excluído");
113 |
114 | } catch (Exception e) {
115 | System.out.println("Posição inválida!");
116 | }
117 | }
118 |
119 | private static void pesquisarContatoExiste(Scanner scan, ArrayList lista){
120 |
121 | int pos = leInformacaoInt("Entre com a posição a ser pesquisada", scan);
122 |
123 | try {
124 |
125 | Contato contato = lista.get(pos);
126 |
127 | boolean existe = lista.contains(contato);
128 |
129 | if (existe){
130 | System.out.println("Contato existe, seguem dados:");
131 | System.out.println(contato);
132 | } else {
133 | System.out.println("Contato não existe");
134 | }
135 |
136 | } catch (Exception e) {
137 | System.out.println("Posição inválida!");
138 | }
139 | }
140 |
141 | private static void pesquisarUltimoIndice(Scanner scan, ArrayList lista){
142 |
143 | int pos = leInformacaoInt("Entre com a posição a ser pesquisada", scan);
144 |
145 | try {
146 |
147 | Contato contato = lista.get(pos);
148 |
149 | System.out.println("Contato existe, seguem dados:");
150 | System.out.println(contato);
151 |
152 | System.out.println("Fazendo pesquisa do último índice do contato encontrado:");
153 | pos = lista.lastIndexOf(contato);
154 |
155 | System.out.println("Contato encontrado na posição " + pos);
156 |
157 | } catch (Exception e) {
158 | System.out.println("Posição inválida!");
159 | }
160 | }
161 |
162 | private static void obtemContato(Scanner scan, ArrayList lista){
163 |
164 | int pos = leInformacaoInt("Entre com a posição a ser pesquisada", scan);
165 |
166 | try {
167 |
168 | Contato contato = lista.get(pos);
169 |
170 | System.out.println("Contato existe, seguem dados:");
171 | System.out.println(contato);
172 |
173 | System.out.println("Fazendo pesquisa do contato encontrado:");
174 | pos = lista.indexOf(contato);
175 |
176 | System.out.println("Contato encontrado na posição " + pos);
177 |
178 | } catch (Exception e) {
179 | System.out.println("Posição inválida!");
180 | }
181 | }
182 |
183 | private static void obtemContatoPosicao(Scanner scan, ArrayList lista){
184 |
185 | int pos = leInformacaoInt("Entre com a posição a ser pesquisada", scan);
186 |
187 | try {
188 |
189 | Contato contato = lista.get(pos);
190 |
191 | System.out.println("Contato existe, seguem dados:");
192 | System.out.println(contato);
193 |
194 | } catch (Exception e) {
195 | System.out.println("Posição inválida!");
196 | }
197 | }
198 |
199 | private static void adicionarContatoFinal(Scanner scan, ArrayList lista){
200 |
201 | System.out.println("Criando um contato, entre com as informações:");
202 | String nome = leInformacao("Entre com o nome", scan);
203 | String telefone = leInformacao("Entre com o telefone", scan);
204 | String email = leInformacao("Entre com o email", scan);
205 |
206 | Contato contato = new Contato(nome, telefone, email);
207 |
208 | lista.add(contato);
209 |
210 | System.out.println("Contato adicionado com sucesso!");
211 | System.out.println(contato);
212 | }
213 |
214 | private static void adicionarContatoPosicao(Scanner scan, ArrayList lista){
215 |
216 | System.out.println("Criando um contato, entre com as informações:");
217 | String nome = leInformacao("Entre com o nome", scan);
218 | String telefone = leInformacao("Entre com o telefone", scan);
219 | String email = leInformacao("Entre com o email", scan);
220 |
221 | Contato contato = new Contato(nome, telefone, email);
222 |
223 | int pos = leInformacaoInt("Entre com a posição a adicionar o contato", scan);
224 |
225 | try {
226 | lista.add(pos, contato);
227 |
228 | System.out.println("Contato adicionado com sucesso!");
229 | System.out.println(contato);
230 |
231 | } catch (Exception e){
232 | System.out.println("Posição inválida, contato não adicionado");
233 | }
234 | }
235 |
236 | private static void criarContatosDinamicamente(int quantidade, ArrayList lista){
237 |
238 | Contato contato;
239 |
240 | for (int i=1; i<=quantidade; i++){
241 |
242 | contato = new Contato();
243 | contato.setNome("Contato " + i);
244 | contato.setTelefone("1111111"+i);
245 | contato.setEmail("contato"+i+"@email.com");
246 |
247 | lista.add(contato);
248 | }
249 | }
250 | }
251 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/vetor/teste/Aula02.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.vetor.teste;
2 |
3 | import com.loiane.estruturadados.vetor.Vetor;
4 |
5 | public class Aula02 {
6 |
7 | public static void main(String[] args) {
8 |
9 | Vetor vetor = new Vetor(5);
10 | }
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/vetor/teste/Aula03.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.vetor.teste;
2 |
3 | import com.loiane.estruturadados.vetor.Vetor;
4 |
5 | public class Aula03 {
6 |
7 | public static void main(String[] args) {
8 |
9 | Vetor vetor = new Vetor(2);
10 |
11 | vetor.adiciona("elemento 1");
12 | vetor.adiciona("elemento 2");
13 | vetor.adiciona("elemento 3");
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/vetor/teste/Aula04.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.vetor.teste;
2 |
3 | import com.loiane.estruturadados.vetor.Vetor;
4 |
5 | public class Aula04 {
6 |
7 | public static void main(String[] args) {
8 |
9 | Vetor vetor = new Vetor(10);
10 |
11 | vetor.adiciona("elemento 1");
12 | vetor.adiciona("elemento 2");
13 | vetor.adiciona("elemento 3");
14 |
15 | System.out.println(vetor.tamanho());
16 |
17 | System.out.println(vetor.toString());
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/vetor/teste/Aula05.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.vetor.teste;
2 |
3 | import com.loiane.estruturadados.vetor.Vetor;
4 |
5 | public class Aula05 {
6 |
7 | public static void main(String[] args) {
8 |
9 | Vetor vetor = new Vetor(10);
10 |
11 | vetor.adiciona("elemento 1"); //0
12 | vetor.adiciona("elemento 2"); //1
13 | vetor.adiciona("elemento 3"); //2
14 |
15 | System.out.println(vetor.busca(3));
16 | }
17 |
18 | }
19 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/vetor/teste/Aula06.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.vetor.teste;
2 |
3 | import com.loiane.estruturadados.vetor.Vetor;
4 |
5 | public class Aula06 {
6 |
7 | public static void main(String[] args) {
8 |
9 | Vetor vetor = new Vetor(10);
10 |
11 | vetor.adiciona("elemento 1"); //0
12 | vetor.adiciona("elemento 2"); //1
13 | vetor.adiciona("elemento 3"); //2
14 |
15 | System.out.println(vetor.busca("elemento 1"));
16 | System.out.println(vetor.busca("elemento 4"));
17 | }
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/vetor/teste/Aula07.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.vetor.teste;
2 |
3 | import com.loiane.estruturadados.vetor.Vetor;
4 |
5 | public class Aula07 {
6 |
7 | public static void main(String[] args) {
8 |
9 | Vetor vetor = new Vetor(10);
10 |
11 | vetor.adiciona("B");
12 | vetor.adiciona("C");
13 | vetor.adiciona("E");
14 | vetor.adiciona("F");
15 | vetor.adiciona("G");
16 |
17 | System.out.println(vetor);
18 |
19 | vetor.adiciona(0, "A");
20 |
21 | System.out.println(vetor);
22 |
23 | vetor.adiciona(3, "D");
24 |
25 | System.out.println(vetor);
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/vetor/teste/Aula08.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.vetor.teste;
2 |
3 | import com.loiane.estruturadados.vetor.Vetor;
4 |
5 | public class Aula08 {
6 |
7 | public static void main(String[] args) {
8 |
9 | Vetor vetor = new Vetor(3);
10 |
11 | vetor.adiciona("B");
12 | vetor.adiciona("C");
13 | vetor.adiciona("E");
14 | vetor.adiciona("F");
15 | vetor.adiciona("G");
16 |
17 | System.out.println(vetor);
18 | }
19 |
20 | }
21 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/vetor/teste/Aula09.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.vetor.teste;
2 |
3 | import com.loiane.estruturadados.vetor.Vetor;
4 |
5 | public class Aula09 {
6 |
7 | public static void main(String[] args) {
8 |
9 | Vetor vetor = new Vetor(3);
10 |
11 | vetor.adiciona("B");
12 | vetor.adiciona("G");
13 | vetor.adiciona("D");
14 | vetor.adiciona("E");
15 | vetor.adiciona("F");
16 |
17 | System.out.println(vetor);
18 |
19 | vetor.remove(1);
20 |
21 | System.out.println(vetor);
22 |
23 | System.out.println("Remover o elemento A");
24 |
25 | int pos = vetor.busca("A");
26 | if (pos > -1){
27 | vetor.remove(pos);
28 | } else {
29 | System.out.println("Elemento não existe no vetor");
30 | }
31 |
32 | System.out.println(vetor);
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/vetor/teste/Aula10.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.vetor.teste;
2 |
3 | import com.loiane.estruturadados.vetor.VetorObjetos;
4 |
5 | public class Aula10 {
6 |
7 | public static void main(String[] args) {
8 |
9 | VetorObjetos vetor = new VetorObjetos(3);
10 |
11 | Contato c1 = new Contato("Contato 1", "1234-4567", "contato1@email.com");
12 | Contato c2 = new Contato("Contato 2", "2345-6789", "contato2@email.com");
13 | Contato c3 = new Contato("Contato 3", "3456-7890", "contato3@email.com");
14 |
15 | Contato c4 = new Contato("Contato 1", "1234-4567", "contato1@email.com");
16 |
17 | vetor.adiciona(c1);
18 | vetor.adiciona(c2);
19 | vetor.adiciona(c3);
20 |
21 | System.out.println("Tamanho = " + vetor.tamanho());
22 |
23 | int pos = vetor.busca(c4);
24 | if (pos > -1){
25 | System.out.println("Elemento existe no vetor");
26 | } else {
27 | System.out.println("Elemento não existe no vetor");
28 | }
29 |
30 | System.out.println(vetor);
31 | }
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/vetor/teste/Aula11.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.vetor.teste;
2 |
3 | import com.loiane.estruturadados.vetor.Lista;
4 | import com.loiane.estruturadados.vetor.VetorObjetos;
5 |
6 | public class Aula11 {
7 |
8 | public static void main(String[] args) {
9 |
10 | Lista vetor = new Lista(1);
11 |
12 | Contato c1 = new Contato("Contato 1", "1234-4567", "contato1@email.com");
13 |
14 | vetor.adiciona(c1);
15 | }
16 |
17 | }
18 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/vetor/teste/Aula12.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.vetor.teste;
2 |
3 | import java.util.ArrayList;
4 |
5 | public class Aula12 {
6 |
7 | public static void main(String[] args) {
8 |
9 | ArrayList arrayList = new ArrayList();
10 |
11 | arrayList.add("A");
12 | arrayList.add("C");
13 |
14 | System.out.println(arrayList);
15 |
16 | arrayList.add(1, "B");
17 |
18 | System.out.println(arrayList);
19 |
20 | boolean existe = arrayList.contains("A");
21 | if (existe){
22 | System.out.println("Elemento existe no array");
23 | } else {
24 | System.out.println("Elemento não existe no array");
25 | }
26 |
27 | int pos = arrayList.indexOf("B");
28 | if (pos > -1){
29 | System.out.println("Elemento existe no array na pos " + pos);
30 | } else {
31 | System.out.println("Elemento não existe no array " + pos);
32 | }
33 |
34 | System.out.println(arrayList.get(2));
35 |
36 | arrayList.remove(0);
37 | arrayList.remove("B");
38 |
39 | System.out.println(arrayList);
40 |
41 | System.out.println(arrayList.size());
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/src/com/loiane/estruturadados/vetor/teste/Contato.java:
--------------------------------------------------------------------------------
1 | package com.loiane.estruturadados.vetor.teste;
2 |
3 | public class Contato {
4 |
5 | private String nome;
6 | private String telefone;
7 | private String email;
8 |
9 | public Contato(String nome, String telefone, String email) {
10 | super();
11 | this.nome = nome;
12 | this.telefone = telefone;
13 | this.email = email;
14 | }
15 |
16 | public Contato() {}
17 |
18 | public String getNome() {
19 | return nome;
20 | }
21 | public void setNome(String nome) {
22 | this.nome = nome;
23 | }
24 | public String getTelefone() {
25 | return telefone;
26 | }
27 | public void setTelefone(String telefone) {
28 | this.telefone = telefone;
29 | }
30 | public String getEmail() {
31 | return email;
32 | }
33 | public void setEmail(String email) {
34 | this.email = email;
35 | }
36 |
37 | @Override
38 | public String toString() {
39 | return "Contato [nome=" + nome + ", telefone=" + telefone + ", email="
40 | + email + "]";
41 | }
42 |
43 | @Override
44 | public int hashCode() {
45 | final int prime = 31;
46 | int result = 1;
47 | result = prime * result + ((email == null) ? 0 : email.hashCode());
48 | result = prime * result + ((nome == null) ? 0 : nome.hashCode());
49 | result = prime * result
50 | + ((telefone == null) ? 0 : telefone.hashCode());
51 | return result;
52 | }
53 |
54 | @Override
55 | public boolean equals(Object obj) {
56 | if (this == obj) {
57 | return true;
58 | }
59 | if (obj == null) {
60 | return false;
61 | }
62 | if (getClass() != obj.getClass()) {
63 | return false;
64 | }
65 | Contato other = (Contato) obj;
66 | if (email == null) {
67 | if (other.email != null) {
68 | return false;
69 | }
70 | } else if (!email.equals(other.email)) {
71 | return false;
72 | }
73 | if (nome == null) {
74 | if (other.nome != null) {
75 | return false;
76 | }
77 | } else if (!nome.equals(other.nome)) {
78 | return false;
79 | }
80 | if (telefone == null) {
81 | if (other.telefone != null) {
82 | return false;
83 | }
84 | } else if (!telefone.equals(other.telefone)) {
85 | return false;
86 | }
87 | return true;
88 | }
89 |
90 |
91 | }
92 |
--------------------------------------------------------------------------------