Escolar Documentos
Profissional Documentos
Cultura Documentos
em CSharp (C#)
por
Versão 1.02
06/10/2014
Bibliografia recomendada
1
Sumário
1. Tipos de Dados 1
1.1 Conceitos Básicos 1
1.1.1 Estruturas de Dados 1
1.1.2 Organização de Arquivos 1
1.1.3 Conceito 1
1.1.4 Dados 1
1.1.5 Tipos de Dados 1
1.2 Tipos Primitivos 2
1.2.1 Tipos primitivos da Linguagem de Programação C# 2
Tabela 1: Tipos de Dados em C# 2
1.3 Construção de Tipos (Estruturados ou Complexos) 3
1.3.1 String (Cadeia de Caracteres) 4
1.3.2 Vetor e Matriz (Agregados Homogêneos) 4
1.3.3 Classe (class) 6
1.4 Operadores (Aritméticos, Relacionais e Lógicos) 7
1.4.1 Aritméticos 7
1.4.2 Relacionais 7
1.4.3 Lógicos 8
2. Vetores e Matrizes 9
2.1 Conceitos Básicos 9
2.2 Exercícios com Vetores e Matrizes 10
2.3 Alocação de Memória (RAM - Random Access Memory) 16
2.3.1 Alocação Estática de Memória 16
2.3.2 Alocação Dinâmica de Memória 17
2.3.3 Célula, Nodo ou Nó 17
3. Listas Lineares 18
3.1 Listas Genéricas 18
3.2 Tipos de Representações 20
3.2.1 Lista Representada por Contiguidade Física 20
3.2.2 Lista representada por Encadeamento 55
3.2.3 Lista Encadeada com Descritor 64
3.2.4 Lista Duplamente Encadeada 72
3.2.5 Listas Lineares com Disciplina de Acesso 79
3.2.5.1 Filas 79
Figura 12: Fila Circular 80
3.2.5.1.1 Fila com Vetor 80
3.2.5.1.2 Fila Circular 83
3.2.5.1.3 Deslocamento dos elementos do vetor 87
3.2.5.1.4 Fila com Alocação Dinâmica 90
3.2.5.2 Pilhas 93
3.2.5.2.1 Pilha com Vetor 93
3.2.5.2.2 Pilha com Alocação Dinâmica 98
3.2.5.3 Deque (“Double-Ended QUEue”) 101
4. Pesquisa de Dados 107
4.1 Pesquisa Seqüencial 107
4.2 Pesquisa Binária 112
4.3 Cálculo de Endereço (Hashing) 116
5.1 Classificação por Força Bruta 121
5.2 Vetor Indireto de Ordenação (Tabela de Índices) 122
5.3 Classificação por Encadeamento 124
5.4 Métodos de Classificação Interna 126
5.4.1 Método por Inserção Direta 127
5.4.2 Método por Troca 129
5.4.2.1 Método da Bolha (Bubble Sort) 129
2
5.4.3 Método por Seleção 131
5.4.3.1 Método por Seleção Direta 131
6. Árvores 134
6.1 Conceitos Básicos 134
6.2 Árvores Binárias 137
6.3 Representações 140
6.3.1 Representação por Contigüidade Física (Adjacência) 140
6.3.2 Representação por Encadeamento 141
6.4 Caminhamento em Árvores 142
6.4.1 Caminhamento Pré-Fixado (Pré-Ordem) 142
6.4.2 Caminhamento In-Fixado (Central) 142
6.4.3 Caminhamento Pós-Fixado 143
6.4.4 Algoritmos recursivos para percorrer Árvores Binárias 143
6.4.4.1 Caminhamento Pré-Fixado (Pré-Ordem) 144
6.4.4.2 Caminhamento In-Fixado (Central) 144
6.4.4.3 Caminhamento Pós-Fixado 144
6.5 Árvore de Busca Binária 146
6.6 Árvore AVL 149
6.6.1 Inserção em uma árvore AVL 150
6.6.2 Remoção em uma árvore AVL 157
7. Grafos 160
7.1 Conceitos 160
7.2 Representação por Lista e Matriz de Adjacências 167
7.2.1 Lista de Adjacências 167
7.2.2 Matriz de Adjacências 168
7.3 Percurso em Amplitude e Percurso em Profundidade 169
7.4 Determinação do Caminho Mínimo 170
7.4.1 Algoritmo de Dijkstra 170
8. Programas exemplos 177
8.1 Torre de Hanoi (Pilha - Stack) 177
8.2 Analisador de Expressões (classes: PilhaInt e PilhaChar) 182
8.3 Analisador de Expressões usando Stack 186
8.4 Calculadora Polonesa Reversa 190
8.5 Torre de Hanoi (classe Pilha) 192
Status: Winner 196
8.6 Jogo Quebra-Cabeças 197
3
1. Tipos de Dados
1.1.3 Conceito
1.1.4 Dados
1
Os tipos de dados podem ser: Primitivos ou Estruturados, sendo que
os estruturados, são também chamados de Complexos.
using System;
namespace Dados1
{
class MainClass
{
public static void Main (string[] args)
{
bool flag = true;
char ch = 'a';
byte b = 10;
short s = 155;
int i = 100;
long l = 123456;
float f = 1.23f; // f significa float
2
double d = 12345.678;
String nome = "Paulo Roberto Gomes Luzzardi";
Console.WriteLine ("boolean: " + flag);
Console.WriteLine ("char: " + ch);
Console.WriteLine ("byte: " + b);
Console.WriteLine ("short: " + s);
Console.WriteLine ("int: " + i);
Console.WriteLine ("long: " + l);
Console.WriteLine ("float: " + f);
Console.WriteLine ("double: " + d);
Console.WriteLine ("String: " + nome);
}
}
}
Resultado do programa:
boolean: True
char: a
byte: 10
short: 155
int: 100
long: 123456
float: 1,23
double: 12345,678
String: Paulo Roberto Gomes Luzzardi
using System;
namespace Dados2
{
class MainClass
{
public static void Main (string[] args)
{
Console.Write("Digite seu Nome: ");
string nome = Console.ReadLine();
Console.WriteLine("Número de Caracteres: {0}", nome.Length);
}
}
}
Resultado do Programa:
3
// ------------------------------------ Agregados Homogêneos
VETOR E MATRIZ: int [] vetor; int [][] matriz;
// ------------------------------------ Classe
CLASSE: public class nomeClasse {
String r = “123.45”;
String s = “abc”;
String t = "Pelotas";
Exemplo:
Exemplos de inicialização:
using System;
namespace Dados3
{
class MainClass
{
public static void Main (string[] args)
{
4
int i, j;
int [] vetor = {10, 20,30, 40, 50};
for (i = 0; i < vetor.Length;i++) {
Console.WriteLine (i + " : " + vetor [i]);
}
const int numeroLinhas = 3;
const int numeroColunas = 2;
int [,] matriz = {{1,2},{3,4},{5,6}};
for (i = 0;i < numeroLinhas;i++) {
for (j = 0; j < numeroColunas; j++) {
Console.WriteLine (i + " : " + j + " : " + matriz [i, j]);
}
}
}
}
}
Resultado do Programa:
0 : 10
1 : 20
2 : 30
3 : 40
4 : 50
0 : 0 : 1
0 : 1 : 2
1 : 0 : 3
1 : 1 : 4
2 : 0 : 5
2 : 1 : 6
using System;
namespace Dados4
{
class MainClass
{
public static void Main (string[] args)
{
int [] vetor = {5, 40, 20, 10, 50, 30}; // 5 é o número de elementos no vetor
5
Console.WriteLine ();
Console.WriteLine ("Número de Elementos: " + vetor[0]);
}
}
}
Resultado do Programa:
Vetor de Entrada: 5 40 20 10 50 30
Vetor Ordenado: 10 20 30 40 50
Número de Elementos: 5
using System;
namespace Dados5
{
class MainClass
{
public static void Main (string[] args)
{
Aluno aluno = new Aluno("Paulo", 10, 'm');
aluno.exibeAtributos();
Console.WriteLine (aluno.toString()); // chamada do método toString
}
}
}
using System;
namespace Dados5
{
public class Aluno
{
// -------------------------------------------- atributos da classe
// ------------------------------------------- construtor
6
// ------------------------------------------- exibeAtributos
// ------------------------------------------- toString
Resultado do Programa:
Nome: Paulo
Matricula: 10
Sexo: Masculino
Paulo ... 10 ... m
1.4.1 Aritméticos
1.4.2 Relacionais
7
Tabela 4: Operadores Relacionais
> Maior
< Menor
>= Maior ou Igual
<= Menor ou Igual
== Igual
!= Diferente
1.4.3 Lógicos
&& e
|| ou
! não
Exemplo:
if (!chuvendo) {
Console.WriteLine ("Está chuvendo");
} else {
Console.WriteLine ("Não está chuvendo");
}
}
8
2. Vetores e Matrizes
9
Entrada de uma Matriz Bidimensional:
using System;
namespace Matriz1
{
class MainClass
{
public static void Main (string[] args)
{
const int numeroLinhas = 3, numeroColunas = 4;
int [, ] a = new int[numeroLinhas, numeroColunas];
int [] sl = new int[numeroLinhas];
int [] sc = new int[numeroColunas];
int k = 0;
for (int l = 0;l < numeroLinhas;l++) {
for (int c = 0;c < numeroColunas;c++) {
sl[k] = sl[k] + a[l, c];
}
k++;
}
Console.WriteLine ();
for (k = 0;k < numeroLinhas;k++) {
Console.WriteLine ("sl[" + (k + 1) + "]: " + sl[k]);
}
k = 0;
for (int c = 0;c < numeroColunas;c++) {
for (int l = 0;l < numeroLinhas;l++) {
10
sc[k] = sc[k] + a[l, c];
}
k++;
}
Console.WriteLine();
for (k = 0;k < numeroColunas;k++) {
Console.WriteLine ("sc[" + (k + 1) + "]: " + sc[k]);
}
Console.WriteLine();
}
}
}
Resultado do Programa:
a [1,1]: 1
a [1,2]: 2
a [1,3]: 3
a [1,4]: 4
a [2,1]: 1
a [2,2]: 2
a [2,3]: 3
a [2,4]: 4
a [3,1]: 5
a [3,2]: 6
a [3,3]: 7
a [3,4]: 8
sl[1]: 10
sl[2]: 10
sl[3]: 26
sc[1]: 7
sc[2]: 10
sc[3]: 13
sc[4]: 16
using System;
namespace Matriz2
{
class MainClass
{
public static void Main (string[] args)
{
const int numeroLinhas = 12, numeroColunas = 13;
float [,] a = {{ 1,1,1,1,1,1,1,1,1,1,1,1,1},
{ 2,1,1,1,1,1,1,1,1,1,1,1,1},
{ 3,1,1,1,1,1,1,1,1,1,1,1,1},
{ 4,1,1,1,1,1,1,1,1,1,1,1,1},
{ 5,1,1,1,1,1,1,1,1,1,1,1,1},
11
{ 6,1,1,1,1,1,1,1,1,1,1,1,1},
{ 7,1,1,1,1,1,1,1,1,1,1,1,1},
{ 8,1,1,1,1,1,1,1,1,1,1,1,1},
{ 9,1,1,1,1,1,1,1,1,1,1,1,1},
{10,1,1,1,1,1,1,1,1,1,1,1,1},
{11,1,1,1,1,1,1,1,1,1,1,1,1},
{12,1,1,1,1,1,1,1,1,1,1,1,1}};
Resultado do Programa:
01,0 -> 1,00 1,00 1,00 1,00 1,00 1,00 1,00 1,00 1,00 1,00 1,00 1,00 1,00
02,0 -> 1,00 0,50 0,50 0,50 0,50 0,50 0,50 0,50 0,50 0,50 0,50 0,50 0,50
03,0 -> 1,00 0,33 0,33 0,33 0,33 0,33 0,33 0,33 0,33 0,33 0,33 0,33 0,33
04,0 -> 1,00 0,25 0,25 0,25 0,25 0,25 0,25 0,25 0,25 0,25 0,25 0,25 0,25
05,0 -> 1,00 0,20 0,20 0,20 0,20 0,20 0,20 0,20 0,20 0,20 0,20 0,20 0,20
06,0 -> 1,00 0,17 0,17 0,17 0,17 0,17 0,17 0,17 0,17 0,17 0,17 0,17 0,17
07,0 -> 1,00 0,14 0,14 0,14 0,14 0,14 0,14 0,14 0,14 0,14 0,14 0,14 0,14
08,0 -> 1,00 0,13 0,13 0,13 0,13 0,13 0,13 0,13 0,13 0,13 0,13 0,13 0,13
09,0 -> 1,00 0,11 0,11 0,11 0,11 0,11 0,11 0,11 0,11 0,11 0,11 0,11 0,11
10,0 -> 1,00 0,10 0,10 0,10 0,10 0,10 0,10 0,10 0,10 0,10 0,10 0,10 0,10
11,0 -> 1,00 0,09 0,09 0,09 0,09 0,09 0,09 0,09 0,09 0,09 0,09 0,09 0,09
12,0 -> 1,00 0,08 0,08 0,08 0,08 0,08 0,08 0,08 0,08 0,08 0,08 0,08 0,08
using System;
namespace Ordenar
{
class MainClass
{
12
public static void Main (string[] args)
{
Vetor vetor = new Vetor(5);
int elemento;
do {
Console.Write ("Elemento: ");
String s = Console.ReadLine();
elemento = Convert.ToInt32(s);
if (elemento != 0) {
vetor.verificaPosicao(elemento);
}
vetor.exibeVetor();
} while (elemento != 0);
}
}
}
using System;
namespace Ordenar
{
public class Vetor
{
private int n, u, max; // atributos da classe
private int [] vet; // atributos da classe
// --------------------------------------------- construtor
// --------------------------------------------- verificaPosicao
// --------------------------------------------- insereFim
13
}
else {
Console.WriteLine ("ERRO: Vetor Lotado");
Environment.Exit(0);
}
}
// --------------------------------------------- insereInicio
// --------------------------------------------- inserePosicao
// --------------------------------------------- exibeVetor
Resultado do Programa:
Elemento: 10
Vetor: [10]
Elemento: 20
Vetor: [10, 20]
Elemento: 30
Vetor: [10, 20, 30]
Elemento: 40
Vetor: [10, 20, 30, 40]
14
Elemento: 50
Vetor: [10, 20, 30, 40, 50]
Elemento: 60
ERRO: Vetor Lotado
using System;
namespace MultMatriz
{
class MainClass
{
public static void Main (string[] args)
{
int ma, na, mb, nb;
if (na != mb) {
Console.WriteLine ("Erro Fatal: Multiplicação Impossível");
Console.WriteLine ("Número de Colunas de A (nA) tem que ser igual número de linhas de B (mB)");
Environment.Exit (0);
}
int [, ] a = new int[ma, na];
int [, ] b = new int[mb, nb];
int [, ] c = new int[ma, nb];
15
for (int k = 0;k < na;k++) {
c[lin, col] = c[lin, col] + a[lin, k] * b[k, col];
}
}
}
Resultado do Programa:
16
float f; // variável “f” ocupa 4 bytes na memória RAM
17
3. Listas Lineares
Conceito
Lista Linear
Exemplos de Listas
18
Operações sobre Listas
1) Percurso
2) Busca
3) Inserção
4) Retirada (Exclusão)
19
Operações Válidas sobre Listas
20
Observação: Como o número de nodos armazenados na lista pode
ser modificado durante a execução do programa, deve-se
representar como parte de um vetor de “m” elementos com “n
<= m”.
const int m = 7;
int [] v = new int [m];
21
elementos é armazenado na posição zero do vetor, ou seja, n =
v[0].
// ---------------------------------------------------------- Fonte: Dados6.cs
using System;
namespace Dados6
{
class MainClass
{
const int SUCESSO = 0;
const int LISTA_CHEIA = 1;
const int LISTA_VAZIA = 2;
// -------------------------------------------------- criaLista
// -------------------------------------------------- incluiFim
if (n < m-1)
{
v[0]++;
v[v[0]] = valor;
return(SUCESSO);
}
else
return(LISTA_CHEIA);
}
// -------------------------------------------------- exibeLista
if (n == 0)
Console.WriteLine ("Erro: Lista Vazia", "Atenção");
else
{
for (int i = 1; i <= n; i++)
s = s + v[i] + " ";
Console.WriteLine ("Lista: " + s);
}
}
criaLista(v);
do {
Console.Write ("Elemento: ");
string s = Console.ReadLine();
valor = Convert.ToInt32(s);
if (valor != 0)
erro = incluiFim(m, v, valor);
22
if (erro == LISTA_CHEIA)
{
Console.WriteLine("Erro: Lista Cheia", "Atenção");
exibeLista(v);
return;
}
Resultado do Programa:
Elemento: 10
Elemento: 20
Elemento: 30
Elemento: 40
Elemento: 50
Elemento: 60
Elemento: 70
Erro: Lista Cheia
Lista: 10 20 30 40 50 60
using System;
namespace Dados6a
{
class MainClass
{
const int SUCESSO = 0;
const int LISTA_CHEIA = 1;
const int LISTA_VAZIA = 2;
do {
Console.Write ("Elemento: ");
string s = Console.ReadLine();
valor = Convert.ToInt32 (s);
if (valor != 0)
erro = lista.incluiFim (valor);
if (erro == LISTA_CHEIA) {
Console.WriteLine ("Erro: Lista Cheia");
lista.exibeLista ();
return;
}
} while (valor != 0);
lista.exibeLista ();
}
}
}
23
// --------------------------------------------------------------------- Lista.cs
using System;
namespace Dados6a
{
// -------------------------------------------------- criaLista
// -------------------------------------------------- incluiFim
if (n < m-1)
{
v[0]++;
v[v[0]] = valor;
return(SUCESSO);
}
else
return(LISTA_CHEIA);
}
// -------------------------------------------------- exibeLista
if (n == 0)
Console.WriteLine ("Erro: Lista Vazia", "Atenção");
else
{
for (int i = 1; i <= n; i++)
s = s + v[i] + " ";
Console.WriteLine ("Lista: " + s);
}
}
}
}
Resultado do Programa:
Elemento: 10
Elemento: 20
Elemento: 30
Elemento: 40
Elemento: 50
Elemento: 60
Elemento: 70
Erro: Lista Cheia
Lista: 10 20 30 40 50 60
24
Problema: Incluir dados em uma lista de números inteiros
(máximo 10 elementos), mantendo-a ordenada.
using System;
namespace Dados7
{
class MainClass
{
// -------------------------------------------------- criaLista
static void criaLista (int[] v)
{
v [0] = 0;
}
// -------------------------------------------------- incluiFim
static int incluiFim (int m, int[] v, int valor)
{
int n = v [0];
if (n < m - 1) {
v [0]++;
v [v [0]] = valor;
return(SUCESSO);
} else
return(LISTA_CHEIA);
}
// -------------------------------------------------- incluiInic
static int incluiInic (int m, int[] v, int valor)
{
int n = v [0];
if (n < m - 1) {
v [0]++;
for (int i = n + 1; i >= 2; i--)
v [i] = v [i - 1];
v [1] = valor;
return(SUCESSO);
} else
return(LISTA_CHEIA);
}
// -------------------------------------------------- incluiPos
static int incluiPos (int m, int[] v, int valor, int pos)
{
int n = v [0];
if (n < m - 1) {
v [0]++;
if (pos == n) {
v [v [0]] = v [n];
v [n] = valor;
} else {
for (int i = n + 1; i >= pos; i--) {
v [i] = v [i - 1];
}
v [pos] = valor;
}
return(SUCESSO);
25
} else
return(LISTA_CHEIA);
}
// -------------------------------------------------- tamanhoLista
static int tamanhoLista (int[] v)
{
return(v [0]);
}
// -------------------------------------------------- verificaPos
static int verificaPos (int m, int[] v, int valor)
{
int i = 1;
do {
if (valor < v [i])
return(incluiPos (m, v, valor, i));
i++;
} while (i <= v [0]);
return(incluiFim (m, v, valor));
}
// -------------------------------------------------- exibeLista
static void exibeLista (int[] v)
{
String s = "";
int n = v [0];
if (n == 0)
Console.WriteLine ("Erro: Lista Vazia");
else {
for (int i = 1; i <= n; i++)
s = s + v [i] + " ";
Console.WriteLine ("Lista: " + s);
}
}
criaLista (v);
Console.Write ("Elemento: ");
string s = Console.ReadLine ();
valor = Convert.ToInt32 (s);
if (valor != 0) {
erro = incluiInic (m, v, valor);
do {
Console.Write ("Elemento: ");
s = Console.ReadLine ();
valor = Convert.ToInt32 (s);
if (valor != 0) {
erro = verificaPos (m, v, valor);
if (erro == LISTA_CHEIA) {
Console.WriteLine ("Erro: Lista Cheia");
exibeLista (v);
return;
}
}
} while (valor != 0);
}
exibeLista (v);
26
}
}
}
Resultado do Programa:
Elemento: 20
Elemento: 40
Elemento: 50
Elemento: 30
Elemento: 10
Elemento: 0
Lista: 10 20 30 40 50
using System;
namespace Dados7a
{
class MainClass
{
public static void Main (string[] args)
{
const int SUCESSO = 0;
const int LISTA_CHEIA = 1;
const int LISTA_VAZIA = 2;
// ------------------------------------------------------------------ ListaOrdenada.cs
27
using System;
namespace Dados7a
{
public class ListaOrdenada
{
const int SUCESSO = 0;
const int LISTA_CHEIA = 1;
const int LISTA_VAZIA = 2;
int[] v;
// -------------------------------------------------- criaLista
public ListaOrdenada (int numElementos)
{
v = new int[numElementos];
v [0] = 0;
}
// -------------------------------------------------- incluiFim
public int incluiFim (int valor)
{
int m = v.Length;
int n = v [0];
if (n < m - 1) {
v [0]++;
v [v [0]] = valor;
return(SUCESSO);
} else
return(LISTA_CHEIA);
}
// -------------------------------------------------- incluiInic
public int incluiInic (int valor)
{
int m = v.Length;
int n = v [0];
if (n < m - 1) {
v [0]++;
for (int i = n + 1; i >= 2; i--)
v [i] = v [i - 1];
v [1] = valor;
return(SUCESSO);
} else
return(LISTA_CHEIA);
}
// -------------------------------------------------- incluiPos
public int incluiPos (int valor, int pos)
{
int m = v.Length;
int n = v [0];
if (n < m - 1) {
v [0]++;
if (pos == n) {
v [v [0]] = v [n];
v [n] = valor;
} else {
for (int i = n + 1; i >= pos; i--) {
v [i] = v [i - 1];
}
v [pos] = valor;
}
return(SUCESSO);
} else
28
return(LISTA_CHEIA);
}
// -------------------------------------------------- tamanhoLista
private int tamanhoLista ()
{
return(v [0]);
}
// -------------------------------------------------- verificaPos
public int verificaPos (int valor)
{
int i = 1;
do {
if (valor < v [i]) {
return(incluiPos (valor, i));
}
i++;
} while (i <= v [0]);
return(incluiFim (valor));
}
// -------------------------------------------------- exibeLista
public void exibeLista ()
{
String s = "";
int n = v [0];
if (n == 0) {
Console.WriteLine ("Erro: Lista Vazia");
} else {
for (int i = 1; i <= n; i++) {
s = s + v [i] + " ";
}
Console.WriteLine ("Lista: " + s);
}
}
}
}
Resultado do Programa:
Elemento: 20
Elemento: 40
Elemento: 50
Elemento: 30
Elemento: 10
Elemento: 0
Lista: 10 20 30 40 50
using System;
namespace Dados8
29
{
class MainClass
{
const int SUCESSO = 0;
const int LISTA_CHEIA = 1;
const int LISTA_VAZIA = 2;
const int REPETIDO = 3;
// -------------------------------------------------- criaLista
static void criaLista (int[] v)
{
v [0] = 0;
}
// -------------------------------------------------- incluiFim
static int incluiFim (int m, int[] v, int valor)
{
int n = v [0];
if (n < m - 1) {
v [0]++;
v [v [0]] = valor;
return(SUCESSO);
} else
return(LISTA_CHEIA);
}
// -------------------------------------------------- incluiInic
static int incluiInic (int m, int[] v, int valor)
{
int n = v [0];
if (n < m - 1) {
v [0]++;
for (int i = n + 1; i >= 2; i--) {
v [i] = v [i - 1];
}
v [1] = valor;
return(SUCESSO);
} else {
return(LISTA_CHEIA);
}
}
// -------------------------------------------------- incluiPos
static int incluiPos (int m, int[] v, int valor, int pos)
{
int n = v [0];
if (n < m - 1) {
v [0]++;
if (pos == n) {
v [v [0]] = v [n];
v [n] = valor;
} else {
for (int i = n + 1; i >= pos; i--) {
v [i] = v [i - 1];
}
v [pos] = valor;
}
return(SUCESSO);
} else {
return(LISTA_CHEIA);
}
}
// -------------------------------------------------- tamanhoLista
static int tamanhoLista (int[] v)
{
return(v [0]);
}
// -------------------------------------------------- verificaPos
30
static int verificaPos (int m, int[] v, int valor)
{
int i = 1;
do {
if (valor == v [i]) {
return(REPETIDO);
}
if (valor < v [i]) {
return(incluiPos (m, v, valor, i));
}
i++;
} while (i <= v [0]);
return(incluiFim (m, v, valor));
}
// -------------------------------------------------- exibeLista
static void exibeLista (int[] v)
{
String s = "";
int n = v [0];
if (n == 0) {
Console.WriteLine ("Erro: Lista Vazia");
} else {
for (int i = 1; i <= n; i++) {
s = s + v [i] + " ";
}
Console.WriteLine ("Lista: " + s);
}
}
criaLista (v);
Console.Write ("Elemento: ");
string s = Console.ReadLine ();
valor = Convert.ToInt32 (s);
if (valor != 0) {
erro = incluiInic (m, v, valor);
do {
Console.Write ("Elemento: ");
s = Console.ReadLine ();
valor = Convert.ToInt32 (s);
if (valor != 0) {
erro = verificaPos (m, v, valor);
switch (erro) {
case REPETIDO:
Console.WriteLine ("Erro: Elemento REPETIDO");
break;
case LISTA_CHEIA:
Console.WriteLine ("Erro: Lista Cheia");
exibeLista (v);
return;
}
}
} while (valor != 0);
}
exibeLista (v);
}
}
}
31
Resultado do Programa:
Elemento: 30
Elemento: 50
Elemento: 20
Elemento: 40
Elemento: 10
Elemento: 0
Lista: 10 20 30 40 50
using System;
namespace Dados8a
{
class MainClass
{
public static void Main (string[] args)
{
const int SUCESSO = 0;
const int LISTA_CHEIA = 1;
const int LISTA_VAZIA = 2;
const int REPETIDO = 3;
32
using System;
namespace Dados8a
{
public class ListaSemRepeticao
{
private int[] v;
const int SUCESSO = 0;
const int LISTA_CHEIA = 1;
const int LISTA_VAZIA = 2;
const int REPETIDO = 3;
// -------------------------------------------------- construtor
public ListaSemRepeticao (int numElementos)
{
v = new int [numElementos];
v [0] = 0;
}
// -------------------------------------------------- incluiFim
public int incluiFim (int valor)
{
int m = v.Length;
int n = v [0];
if (n < m - 1) {
v [0]++;
v [v [0]] = valor;
return(SUCESSO);
} else {
return(LISTA_CHEIA);
}
}
// -------------------------------------------------- incluiInic
public int incluiInic (int valor)
{
int m = v.Length;
int n = v [0];
if (n < m - 1) {
v [0]++;
for (int i = n + 1; i >= 2; i--) {
v [i] = v [i - 1];
}
v [1] = valor;
return(SUCESSO);
} else {
return(LISTA_CHEIA);
}
}
// -------------------------------------------------- incluiPos
public int incluiPos (int valor, int pos)
{
int m = v.Length;
int n = v [0];
if (n < m - 1) {
v [0]++;
if (pos == n) {
v [v [0]] = v [n];
v [n] = valor;
} else {
for (int i = n + 1; i >= pos; i--) {
v [i] = v [i - 1];
}
v [pos] = valor;
}
return(SUCESSO);
} else {
33
return(LISTA_CHEIA);
}
}
// -------------------------------------------------- tamanhoLista
public int tamanhoLista ()
{
return(v [0]);
}
// -------------------------------------------------- verificaPos
public int verificaPos (int valor)
{
int i = 1;
do {
if (valor == v [i]) {
return(REPETIDO);
}
if (valor < v [i]) {
return(incluiPos (valor, i));
}
i++;
} while (i <= v [0]);
return(incluiFim (valor));
}
// -------------------------------------------------- exibeLista
public void exibeLista ()
{
String s = "";
int n = v [0];
if (n == 0) {
Console.WriteLine ("Erro: Lista Vazia");
} else {
for (int i = 1; i <= n; i++) {
s = s + v [i] + " ";
}
Console.WriteLine ("Lista: " + s);
}
}
}
}
Resultado do Programa:
Elemento: 30
Elemento: 50
Elemento: 20
Elemento: 40
Elemento: 10
Elemento: 0
Lista: 10 20 30 40 50
Contiguidade Física
34
Observação: As operações de inclusão e exclusão de nodos
podem optar pela extremidade da lista que irá diminuir (no
caso de exclusão) ou aumentar (no caso de inserção) de
comprimento. “A escolha deverá considerar o caso que produz
menor movimentação de elementos”.
const int m = 7;
int inicio;
int fim;
int []v = new int[m];
ou
const int m = 7;
int []v = new int[m + 2];
Lista vazia
início = -1
fim = -1
Lista cheia
início = 0
fim = m - 1
metade =(m / 2) + 1
inic fim
+-------------------------------------+
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
+-------------------------------------+
| -1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | -1 |
+-------------------------------------+
|---------------------------- v -------------|
Figura 8: Lista Linear
35
// ------------------------------------------------------ Fonte: Dados9.cs
namespace Dados9
{
class MainClass
{
const int SUCESSO = 0;
const int LISTA_CHEIA = 1;
const int LISTA_VAZIA = 2;
// ---------------------------------------------- Cria_Lista
static void criaLista (int[] v)
{
int inic = 0;
int fim = v.Length - 1;
v [inic] = -1;
v [fim] = -1;
}
// ---------------------------------------------- Inclui_Inicio
static int incluiInicio (int[] v, int dado)
{
int inic = v [0];
int fim = v [v.Length - 1];
int m = v.Length - 2;
int metade = (m / 2) + 1;
if (inic == -1) {
inic = metade;
fim = inic;
v [inic] = dado;
v [0] = inic;
v [v.Length - 1] = fim;
return (SUCESSO);
} else {
if (inic == 1) {
return (LISTA_CHEIA);
} else {
inic--;
v [inic] = dado;
v [0] = inic;
return (SUCESSO);
}
}
}
// ---------------------------------------------- Inclui_Fim
static int incluiFim (int[] v, int dado)
{
int inic = v [0];
int fim = v [v.Length - 1];
int m = v.Length - 2;
int metade = (m / 2) + 1;
if (fim == -1) {
inic = metade;
fim = inic;
v [fim] = dado;
v [0] = inic;
v [v.Length - 1] = fim;
return (SUCESSO);
} else {
if (fim == m) {
return (LISTA_CHEIA);
} else {
fim++;
v [fim] = dado;
v [v.Length - 1] = fim;
return (SUCESSO);
36
}
}
}
// ---------------------------------------------- Imprime_Erro
static void imprimeErro (int erro)
{
switch (erro) {
case LISTA_VAZIA:
Console.WriteLine ("ERRO: Lista Vazia");
break;
case LISTA_CHEIA:
Console.WriteLine ("ERRO: Lista Cheia");
break;
}
}
// ---------------------------------------------- Exibe_Lista
static void exibeLista (int[] v)
{
int inic = v [0];
int fim = v [v.Length - 1];
criaLista (v);
do {
exibeLista (v);
Console.Write ("\nValor: ");
String s = Console.ReadLine ();
valor = Convert.ToInt32 (s);
if (valor != 0) {
Console.Write ("[I]nício ou [F]im ?");
do {
s = Console.ReadLine ();
ch = s [0];
} while (ch != 'I' && ch != 'i' && ch != 'F' && ch != 'f');
}
switch (ch) {
case 'I':
case 'i':
erro = incluiInicio (v, valor);
break;
case 'F':
case 'f':
erro = incluiFim (v, valor);
break;
}
if (erro != SUCESSO) {
37
imprimeErro (erro);
}
} while (valor != 0 && erro != LISTA_CHEIA);
exibeLista (v);
}
}
}
Resultado do Programa:
inic: -1
fim: -1
indices: 0 1 2 3 4 5 6 7 8
Lista: -1 0 0 0 0 0 0 0 -1
Valor: 10
[I]nício ou [F]im ?i
inic: 4
fim: 4
indices: 0 1 2 3 4 5 6 7 8
Lista: 4 0 0 0 10 0 0 0 4
Valor: 20
[I]nício ou [F]im ?f
inic: 4
fim: 5
indices: 0 1 2 3 4 5 6 7 8
Lista: 4 0 0 0 10 20 0 0 5
Valor: 30
[I]nício ou [F]im ?f
inic: 4
fim: 6
indices: 0 1 2 3 4 5 6 7 8
Lista: 4 0 0 0 10 20 30 0 6
Valor: 0
inic: 4
fim: 7
indices: 0 1 2 3 4 5 6 7 8
Lista: 4 0 0 0 10 20 30 0 7
using System;
namespace Dados9a
{
class MainClass
{
public static void Main (string[] args)
{
const int SUCESSO = 0;
const int LISTA_CHEIA = 1;
const int LISTA_VAZIA = 2;
38
do {
lista.exibeLista ();
Console.Write ("\nValor: ");
s = Console.ReadLine ();
valor = Convert.ToInt32 (s);
if (valor != 0) {
Console.Write ("[I]nício ou [F]im ?");
do {
s = Console.ReadLine ();
ch = s [0];
} while (ch != 'I' && ch != 'i' && ch != 'F' && ch != 'f');
}
switch (ch) {
case 'I':
case 'i':
erro = lista.incluiInicio (valor);
break;
case 'F':
case 'f':
erro = lista.incluiFim (valor);
break;
}
if (erro != SUCESSO) {
lista.imprimeErro (erro);
}
} while (valor != 0 && erro != LISTA_CHEIA);
lista.exibeLista ();
}
}
}
using System;
namespace Dados9a
{
public class ListaLinear
{
private int[] v;
const int SUCESSO = 0;
const int LISTA_CHEIA = 1;
const int LISTA_VAZIA = 2;
// ---------------------------------------------- construtor
public ListaLinear (int numElementos)
{
v = new int[numElementos + 2]; // v[0] = inic e v[m] = fim
int inic = 0;
int fim = v.Length - 1;
v [inic] = -1;
v [fim] = -1;
}
// ---------------------------------------------- incluiInicio
public int incluiInicio (int dado)
{
int inic = v [0];
int fim = v [v.Length - 1];
int m = v.Length - 2;
int metade = (m / 2) + 1;
if (inic == -1) {
inic = metade;
fim = inic;
v [inic] = dado;
v [0] = inic;
v [v.Length - 1] = fim;
return (SUCESSO);
39
} else {
if (inic == 1) {
return (LISTA_CHEIA);
} else {
inic--;
v [inic] = dado;
v [0] = inic;
return (SUCESSO);
}
}
}
// ---------------------------------------------- incluiFim
public int incluiFim (int dado)
{
int inic = v [0];
int fim = v [v.Length - 1];
int m = v.Length - 2;
int metade = (m / 2) + 1;
if (fim == -1) {
inic = metade;
fim = inic;
v [fim] = dado;
v [0] = inic;
v [v.Length - 1] = fim;
return (SUCESSO);
} else {
if (fim == m) {
return (LISTA_CHEIA);
} else {
fim++;
v [fim] = dado;
v [v.Length - 1] = fim;
return (SUCESSO);
}
}
}
// ---------------------------------------------- imprimeErro
public void imprimeErro (int erro)
{
switch (erro) {
case LISTA_VAZIA:
Console.WriteLine ("ERRO: Lista Vazia");
break;
case LISTA_CHEIA:
Console.WriteLine ("ERRO: Lista Cheia");
break;
}
}
// ---------------------------------------------- exibeLista
public void exibeLista ()
{
int inic = v [0];
int fim = v [v.Length - 1];
40
}
}
Resultado do Programa:
inic: -1
fim: -1
indices: 0 1 2 3 4 5 6 7 8
Lista: -1 0 0 0 0 0 0 0 -1
Valor: 10
[I]nício ou [F]im ?f
inic: 4
fim: 4
indices: 0 1 2 3 4 5 6 7 8
Lista: 4 0 0 0 10 0 0 0 4
Valor: 20
[I]nício ou [F]im ?f
inic: 4
fim: 5
indices: 0 1 2 3 4 5 6 7 8
Lista: 4 0 0 0 10 20 0 0 5
Valor: 5
[I]nício ou [F]im ?i
inic: 3
fim: 5
indices: 0 1 2 3 4 5 6 7 8
Lista: 3 0 0 5 10 20 0 0 5
Valor: 0
inic: 2
fim: 5
indices: 0 1 2 3 4 5 6 7 8
Lista: 2 0 0 5 10 20 0 0 5
Observação: Note que a lista pode estar cheia num lado e não
estar cheia no outro lado. A próxima solução (10) avisa ao
usuário qual lado da lista linear está cheia.
using System;
namespace Dados10
{
class MainClass
{
const int SUCESSO = 0;
const int LISTA_CHEIA_DIREITA = 1;
const int LISTA_CHEIA_ESQUERDA = 2;
// ---------------------------------------------- Cria_Lista
static void criaLista(int[] v) {
int inic = 0;
int fim = v.Length - 1;
41
v[inic] = -1;
v[fim] = -1;
}
// ---------------------------------------------- Inclui_Inicio
static int incluiInicio(int[] v, int dado) {
int inic = v[0];
int fim = v[v.Length - 1];
int m = v.Length - 2;
int metade = (m / 2) + 1;
if (inic == -1) {
inic = metade;
fim = inic;
v[inic] = dado;
v[0] = inic;
v[v.Length - 1] = fim;
return (SUCESSO);
} else {
if (inic == 1) {
return (LISTA_CHEIA_ESQUERDA);
} else {
inic--;
v[inic] = dado;
v[0] = inic;
return (SUCESSO);
}
}
}
// ---------------------------------------------- Inclui_Fim
static int incluiFim(int[] v, int dado) {
int inic = v[0];
int fim = v[v.Length - 1];
int m = v.Length - 2;
int metade = (m / 2) + 1;
if (fim == -1) {
inic = metade;
fim = inic;
v[fim] = dado;
v[0] = inic;
v[v.Length - 1] = fim;
return (SUCESSO);
} else {
if (fim == m) {
return (LISTA_CHEIA_DIREITA);
} else {
fim++;
v[fim] = dado;
v[v.Length - 1] = fim;
return (SUCESSO);
}
}
}
// ---------------------------------------------- Imprime_Erro
static void imprimeErro(int erro) {
switch (erro) {
case LISTA_CHEIA_ESQUERDA:
Console.WriteLine ("ERRO: Lista Cheia a Esquerda");
break;
case LISTA_CHEIA_DIREITA:
Console.WriteLine ("ERRO: Lista Cheia a Direita");
break;
}
42
}
// ---------------------------------------------- Exibe_Lista
static void exibeLista(int[] v) {
int inic = v[0];
int fim = v[v.Length - 1];
criaLista(v);
do {
exibeLista(v);
Console.Write ("\nValor: ");
String s = Console.ReadLine();
valor = Convert.ToInt32(s);
if (valor != 0) {
Console.Write ("[I]nício ou [F]im ?");
do {
s = Console.ReadLine();
ch = s[0];
} while (ch != 'I' && ch != 'i' && ch != 'F' && ch != 'f');
}
switch (ch) {
case 'I':
case 'i':
erro = incluiInicio(v, valor);
break;
case 'F':
case 'f':
erro = incluiFim(v, valor);
break;
}
if (erro != SUCESSO) {
imprimeErro(erro);
}
} while (valor != 0);
exibeLista(v);
}
}
}
Resultado do Programa:
inic: -1
fim: -1
indices: 0 1 2 3 4 5 6 7 8
Lista: -1 0 0 0 0 0 0 0 -1
Valor: 10
43
[I]nício ou [F]im ?f
inic: 4
fim: 4
indices: 0 1 2 3 4 5 6 7 8
Lista: 4 0 0 0 10 0 0 0 4
Valor: 20
[I]nício ou [F]im ?f
inic: 4
fim: 5
indices: 0 1 2 3 4 5 6 7 8
Lista: 4 0 0 0 10 20 0 0 5
Valor: 5
[I]nício ou [F]im ?i
inic: 3
fim: 5
indices: 0 1 2 3 4 5 6 7 8
Lista: 3 0 0 5 10 20 0 0 5
Valor: 0
inic: 2
fim: 5
indices: 0 1 2 3 4 5 6 7 8
Lista: 2 0 0 5 10 20 0 0 5
using System;
namespace Dados10a
{
class MainClass
{
do {
lista.exibeLista();
Console.Write ("\nValor: ");
String s = Console.ReadLine();
valor = Convert.ToInt32(s);
if (valor != 0) {
Console.Write ("[I]nício ou [F]im ?");
do {
s = Console.ReadLine();
ch = s[0];
} while (ch != 'I' && ch != 'i' && ch != 'F' && ch != 'f');
}
switch (ch) {
case 'I':
case 'i': erro = lista.incluiInicio(valor);
break;
case 'F':
44
case 'f': erro = lista.incluiFim(valor);
break;
}
if (erro != SUCESSO) {
lista.imprimeErro(erro);
}
} while (valor != 0);
lista.exibeLista();
}
}
}
using System;
namespace Dados10a
{
public class ListaLinear
{
private int [] v;
private const int SUCESSO = 0;
private const int LISTA_CHEIA_DIREITA = 1;
private const int LISTA_CHEIA_ESQUERDA = 2;
// ---------------------------------------------- construtor
v[inic] = -1;
v[fim] = -1;
}
// ---------------------------------------------- incluiInicio
if (inic == -1) {
inic = metade;
fim = inic;
v[inic] = dado;
v[0] = inic;
v[v.Length - 1] = fim;
return(SUCESSO);
}
else {
if (inic == 1) {
return(LISTA_CHEIA_ESQUERDA);
}
else {
inic--;
v[inic] = dado;
v[0] = inic;
return(SUCESSO);
}
}
}
// ---------------------------------------------- incluiFim
45
public int incluiFim(int dado) {
int inic = v[0];
int fim = v[v.Length - 1];
int m = v.Length - 2;
int metade = (m / 2) + 1;
if (fim == -1) {
inic = metade;
fim = inic;
v[fim] = dado;
v[0] = inic;
v[v.Length - 1] = fim;
return(SUCESSO);
}
else {
if (fim == m) {
return(LISTA_CHEIA_DIREITA);
}
else {
fim++;
v[fim] = dado;
v[v.Length - 1] = fim;
return(SUCESSO);
}
}
}
// ---------------------------------------------- imprimeErro
// ---------------------------------------------- exibeLista
Resultado do Programa:
inic: -1
fim: -1
indices: 0 1 2 3 4 5 6 7 8
Lista: -1 0 0 0 0 0 0 0 -1
Valor: 10
[I]nício ou [F]im ?f
inic: 4
46
fim: 4
indices: 0 1 2 3 4 5 6 7 8
Lista: 4 0 0 0 10 0 0 0 4
Valor: 20
[I]nício ou [F]im ?f
inic: 4
fim: 5
indices: 0 1 2 3 4 5 6 7 8
Lista: 4 0 0 0 10 20 0 0 5
Valor: 5
[I]nício ou [F]im ?i
inic: 3
fim: 5
indices: 0 1 2 3 4 5 6 7 8
Lista: 3 0 0 5 10 20 0 0 5
Valor: 0
inic: 2
fim: 5
indices: 0 1 2 3 4 5 6 7 8
Lista: 2 0 0 5 10 20 0 0 5
using System;
namespace Dados11
{
class MainClass
{
const int SUCESSO = 0;
const int LISTA_CHEIA = 1;
const int LISTA_VAZIA = 2;
const int POSICAO_INVALIDA = 3;
// ---------------------------------------------- criaLista
static void criaLista (int[]v)
{
int inic = 0;
int fim = v.Length - 1;
v [inic] = -1;
v [fim] = -1;
}
// ---------------------------------------------- incluiInicio
static int incluiInicio (int[] v, int dado)
{
int inic = v [0];
int fim = v [v.Length - 1];
int m = v.Length - 2;
int metade = (m / 2) + 1;
if (inic == -1) {
inic = metade;
fim = inic;
v [inic] = dado;
v [0] = inic;
47
v [v.Length - 1] = fim;
return(SUCESSO);
} else {
if (inic == 1) {
return(LISTA_CHEIA);
} else {
inic--;
v [inic] = dado;
v [0] = inic;
return(SUCESSO);
}
}
}
// ---------------------------------------------- incluiFim
static int incluiFim (int[] v, int dado)
{
int inic = v [0];
int fim = v [v.Length - 1];
int m = v.Length - 2;
int metade = (m / 2) + 1;
if (fim == -1) {
inic = metade;
fim = inic;
v [fim] = dado;
v [0] = inic;
v [v.Length - 1] = fim;
return(SUCESSO);
} else {
if (fim == m) {
return(LISTA_CHEIA);
} else {
fim++;
v [fim] = dado;
v [v.Length - 1] = fim;
return(SUCESSO);
}
}
}
// ---------------------------------------------- incluiPosicao
static int incluiPosicao (int[] v, int dado, int pos)
{
int erro;
int inic = v [0];
int fim = v [v.Length - 1];
int m = v.Length - 2;
48
return(erro);
} else {
for (int i = fim; i >= pos; i--) {
v [i + 1] = v [i];
}
v [pos] = dado;
fim++;
v [0] = inic;
v [v.Length - 1] = fim;
return(SUCESSO);
}
}
}
}
}
// ---------------------------------------------- imprimeErro
static void imprimeErro (int erro)
{
switch (erro) {
case LISTA_CHEIA:
Console.WriteLine ("ERRO: Lista Cheia");
break;
case LISTA_VAZIA:
Console.WriteLine ("ERRO: Lista Vazia");
break;
case POSICAO_INVALIDA:
Console.WriteLine ("ERRO: Posição Inválida");
break;
}
}
// ---------------------------------------------- exibeLista
static void exibeLista (int[] v)
{
int inic = v [0];
int fim = v [v.Length - 1];
const int m = 7;
int[] v = new int[m + 2]; // v[0] = inic e v[m] = fim
int valor, pos;
int erro = SUCESSO;
char ch = 'A';
criaLista (v);
do {
exibeLista (v);
Console.Write ("\nValor: ");
String s = Console.ReadLine ();
valor = Convert.ToInt32 (s);
if (valor != 0) {
Console.Write ("[I]nício, [P]osição ou [F]im ?");
do {
49
s = Console.ReadLine ();
ch = s [0];
} while (ch != 'I' && ch != 'i' &&
ch != 'P' && ch != 'p' && ch != 'F' && ch != 'f');
}
switch (ch) {
case 'I':
case 'i':
erro = incluiInicio (v, valor);
break;
case 'F':
case 'f':
erro = incluiFim (v, valor);
break;
case 'P':
case 'p':
Console.Write ("Posição: ");
s = Console.ReadLine ();
pos = Convert.ToInt32 (s);
erro = incluiPosicao (v, valor, pos);
break;
}
if (erro != SUCESSO) {
imprimeErro (erro);
}
} while (valor != 0);
exibeLista (v);
}
}
}
Resultado do Programa:
inic: -1
fim: -1
indices: 0 1 2 3 4 5 6 7 8
Lista: -1 0 0 0 0 0 0 0 -1
Valor: 10
[I]nício, [P]osicao ou [F]im ?f
inic: 4
fim: 4
indices: 0 1 2 3 4 5 6 7 8
Lista: 4 0 0 0 10 0 0 0 4
Valor: 20
[I]nício, [P]osicao ou [F]im ?f
inic: 4
fim: 5
indices: 0 1 2 3 4 5 6 7 8
Lista: 4 0 0 0 10 20 0 0 5
Valor: 5
[I]nício, [P]osicao ou [F]im ?i
inic: 3
fim: 5
indices: 0 1 2 3 4 5 6 7 8
Lista: 3 0 0 5 10 20 0 0 5
Valor: 0
inic: 2
fim: 5
indices: 0 1 2 3 4 5 6 7 8
Lista: 2 0 0 5 10 20 0 0 5
50
de uma lista linear. O programa possui uma classe
ListaLinear.
// ------------------------------------------------------------------- Fonte: Dados11a.cs
using System;
namespace Dados11a
{
class MainClass
{
public static void Main (string[] args)
{
const int SUCESSO = 0;
const int LISTA_CHEIA = 1;
const int LISTA_VAZIA = 2;
const int POSICAO_INVALIDA = 3;
do {
lista.exibeLista ();
Console.Write ("\nValor: ");
String s = Console.ReadLine ();
valor = Convert.ToInt32 (s);
if (valor != 0) {
Console.Write ("[I]nício, [P]osição ou [F]im ?");
do {
s = Console.ReadLine ();
ch = s [0];
} while (!strChr ("IiPpFf", ch));
}
switch (ch) {
case 'I':
case 'i':
erro = lista.incluiInicio (valor);
break;
case 'F':
case 'f':
erro = lista.incluiFim (valor);
break;
case 'P':
case 'p':
Console.Write ("Posição: ");
s = Console.ReadLine ();
pos = Convert.ToInt32 (s);
erro = lista.incluiPosicao (valor, pos);
break;
}
if (erro != SUCESSO) {
lista.imprimeErro (erro);
}
} while (valor != 0);
lista.exibeLista ();
}
// ----------------------------------------------- strChr
static bool strChr (String s, char ch)
{
int n = s.Length;
51
}
}
return(false);
}
}
}
// ---------------------------------------------------------------- ListaLinear.cs
using System;
namespace Dados11a
{
public class ListaLinear
{
private int [] v;
const int SUCESSO = 0;
const int LISTA_CHEIA = 1;
const int LISTA_VAZIA = 2;
const int POSICAO_INVALIDA = 3;
// --------------------------------------------- construtor
// ---------------------------------------------- incluiInicio
if (inic == -1) {
inic = metade;
fim = inic;
v[inic] = dado;
v[0] = inic;
v[v.Length - 1] = fim;
return(SUCESSO);
}
else {
if (inic == 1) {
return(LISTA_CHEIA);
}
else {
inic--;
v[inic] = dado;
v[0] = inic;
return(SUCESSO);
}
}
}
// ---------------------------------------------- incluiFim
52
if (fim == -1) {
inic = metade;
fim = inic;
v[fim] = dado;
v[0] = inic;
v[v.Length - 1] = fim;
return(SUCESSO);
}
else {
if (fim == m) {
return(LISTA_CHEIA);
}
else {
fim++;
v[fim] = dado;
v[v.Length - 1] = fim;
return(SUCESSO);
}
}
}
// ---------------------------------------------- incluiPosicao
53
}
}
// ---------------------------------------------- imprimeErro
// ---------------------------------------------- exibeLista
Resultado do Programa:
inic: -1
fim: -1
indices: 0 1 2 3 4 5 6 7 8
Lista: -1 0 0 0 0 0 0 0 -1
Valor: 10
[I]nício, [P]osição ou [F]im ?f
inic: 4
fim: 4
indices: 0 1 2 3 4 5 6 7 8
Lista: 4 0 0 0 10 0 0 0 4
Valor: 20
[I]nício, [P]osição ou [F]im ?f
inic: 4
fim: 5
indices: 0 1 2 3 4 5 6 7 8
Lista: 4 0 0 0 10 20 0 0 5
Valor: 5
[I]nício, [P]osição ou [F]im ?i
inic: 3
fim: 5
indices: 0 1 2 3 4 5 6 7 8
Lista: 3 0 0 5 10 20 0 0 5
Valor: 0
inic: 2
fim: 5
indices: 0 1 2 3 4 5 6 7 8
Lista: 2 0 0 5 10 20 0 0 5
54
Vantagens e Desvantagens da Representação por Contigüidade Física
Vantagens
Desvantagens
using System;
using System.Collections.Generic;
namespace Dados12
{
class MainClass
55
{
public static void Main (string[] args)
{
LinkedList<string> lista = new LinkedList<string>();
lista.AddFirst("Ana"); // adiciona o primeiro elemento
lista.AddLast ("Beatriz");
lista.AddLast ("Carla");
lista.AddLast ("Debora");
Resultado do Programa:
Ana
Beatriz
Carla
Debora
using System;
using System.Collections.Generic;
namespace Dados13
{
class MainClass
{
public static void Main (string[] args)
{
LinkedList <int> lista = new LinkedList<int> ();
Resultado do Programa:
56
Nodo: 10
Nodo: 20
Nodo: 30
Nodo: 40
Nodo: 50
Nodo: 0
Lista: 10 20 30 40 50
using System;
namespace Dados14
{
public class Nodo
{
public int dado;
public Nodo elo = null;
}
}
using System;
namespace Dados14
{
public class ListaEncadeada
{
private Nodo prim;
private int n;
private Nodo ult;
// ------------------------------- construtor
public ListaEncadeada ()
{
prim = null;
n = 0;
ult = null;
}
// ------------------------------- inserirLista
57
public void inserirLista (int chave)
{
Nodo aux = new Nodo ();
aux.dado = chave;
if (prim == null) {
prim = aux;
} else {
ult.elo = aux;
}
n++;
ult = aux;
}
// ------------------------------- removerLista
public int removerLista ()
{
using System;
namespace Dados14
{
class MainClass
{
public static void Main (string[] args)
{
ListaEncadeada lista = new ListaEncadeada();
int dado;
58
do {
Console.Write ("Dado: ");
String s = Console.ReadLine();
dado = Convert.ToInt32(s);
if (dado != 0) {
lista.inserirLista(dado);
}
} while (dado != 0);
lista.imprimirLista();
int n = lista.contaElementosLista();
Console.WriteLine ("Total de Elementos: " + n);
dado = lista.removerLista();
while (dado != 0) {
Console.WriteLine ("Dado Removido: " + dado);
dado = lista.removerLista();
}
n = lista.contaElementosLista();
Console.WriteLine ("Total de Elementos: " + n);
lista.imprimirLista();
}
}
}
Resultado do Programa:
Dado: 10
Dado: 20
Dado: 30
Dado: 40
Dado: 50
Dado: 0
Lista Encadeada: [ 10 20 30 40 50 ]
Total de Elementos: 5
Dado Removido: 10
Dado Removido: 20
Dado Removido: 30
Dado Removido: 40
Dado Removido: 50
Total de Elementos: 0
Lista Encadeada: [ Vazia]
59
Problema: Escrever um programa em C# que insere dados em uma
lista encadeada simples, permitindo obter o conteúdo do
último elemento, imprimindo também, toda a lista.
using System;
namespace Dados15
{
public class Nodo
{
public int dado;
public Nodo elo = null;
}
}
using System;
namespace Dados15
{
public class ListaEncadeadaSimples
{
private Nodo primeiro = null;
// ------------------------------- inserirLista
public void inserirLista (int valor)
{
Nodo aux = new Nodo ();
Nodo tmp;
aux.dado = valor;
if (primeiro == null) {
primeiro = aux;
} else {
tmp = primeiro;
aux.elo = tmp;
primeiro = aux;
}
}
// ------------------------------- removerLista
public int removerLista ()
{
Nodo aux;
int dado;
aux = primeiro;
if (aux != null) {
dado = primeiro.dado;
primeiro = primeiro.elo;
return(dado);
} else
return(0);
}
// ------------------------------- imprimirLista
public void imprimirLista ()
{
60
Nodo aux;
aux = primeiro;
using System;
namespace Dados15
{
class MainClass
{
public static void Main (string[] args)
{
ListaEncadeadaSimples lista = new ListaEncadeadaSimples();
int dado;
do {
Console.Write ("Dado: ");
String s = Console.ReadLine();
dado = Convert.ToInt32(s);
if (dado != 0) {
lista.inserirLista(dado);
}
} while (dado != 0);
lista.imprimirLista();
dado = lista.removerLista();
while (dado != 0) {
Console.WriteLine ("Dado Removido: " + dado);
dado = lista.removerLista();
}
}
}
}
Resultado do Programa:
Dado: 10
Dado: 20
Dado: 30
Dado: 40
Dado: 50
Dado: 0
Lista Encadeada Simples: 50 40 30 20 10
Dado Removido: 50
Dado Removido: 40
Dado Removido: 30
Dado Removido: 20
Dado Removido: 10
61
Problema: Escrever um programa em C# que permite incluir,
excluir e consultar (no início ou fim) dados inteiros em uma
lista encadeada. Em cada operação imprimir a lista.
using System;
namespace Dados16
{
public class Nodo
{
public int dado;
public Nodo elo = null;
}
}
using System;
namespace Dados16
{
public class ListaEncadeada
{
private Nodo primeiro = null;
// ------------------------------- inserirLista
public void inserirLista (int valor)
{
Nodo aux = new Nodo ();
Nodo tmp;
aux.dado = valor;
if (primeiro == null) {
primeiro = aux;
} else {
tmp = primeiro;
aux.elo = tmp;
primeiro = aux;
}
}
// ------------------------------- removerLista
public int removerLista ()
{
Nodo aux;
int dado;
aux = primeiro;
if (aux != null) {
dado = primeiro.dado;
primeiro = primeiro.elo;
return(dado);
} else
return(0);
}
// ------------------------------- consultarLista
62
public int consultarLista ()
{
Nodo aux;
aux = primeiro;
if (aux != null) {
return(primeiro.dado);
} else
return(0);
}
// ------------------------------- imprimirLista
public void imprimirLista ()
{
Nodo aux;
aux = primeiro;
using System;
namespace Dados16
{
class MainClass
{
public static void Main (string[] args)
{
ListaEncadeada lista = new ListaEncadeada ();
char op;
int dado = 0;
do {
Console.Write ("[I]ncluir, [C]onsultar, [R]emover ou [F]im: ");
do {
String s = Console.ReadLine ();
s = s.ToLower ();
op = s [0];
} while (op != 'i' && op != 'c' && op != 'r' && op != 'f');
switch (op) {
case 'i':
Console.Write ("Dado: ");
String s = Console.ReadLine ();
dado = Convert.ToInt32 (s);
if (dado != 0) {
lista.inserirLista (dado);
}
break;
case 'c':
dado = lista.consultarLista ();
Console.WriteLine ("Dado Consultado: " + dado);
break;
63
case 'r':
dado = lista.removerLista ();
Console.WriteLine ("Dado Removido: " + dado);
break;
}
lista.imprimirLista ();
} while (op != 'f');
}
}
}
Resultado do Programa:
64
o último elemento. Estas dificuldades podem ser resolvidas
utilizando-se um descritor, da seguinte forma:
using System;
namespace Dados17
{
public class Nodo
{
public int dado;
public Nodo elo = null;
}
}
using System;
namespace Dados17
{
public class ListaEncadeadaDescritor
{
private Nodo primeiro;
private int n;
private Nodo ultimo;
// ------------------------------- construtor
public ListaEncadeadaDescritor ()
{
primeiro = null;
n = 0;
ultimo = null;
}
65
// ------------------------------- inserirListaEsquerda
public void inserirListaEsquerda (int valor)
{
Nodo aux = new Nodo ();
aux.dado = valor;
if (n == 0) {
primeiro = aux;
ultimo = aux;
aux.elo = null;
} else {
aux.elo = primeiro;
primeiro = aux;
}
n++;
}
// ------------------------------- inserirListaDireita
public void inserirListaDireita (int valor)
{
Nodo aux = new Nodo ();
Nodo tmp;
aux.dado = valor;
if (n == 0) {
primeiro = aux;
ultimo = aux;
} else {
tmp = ultimo;
tmp.elo = aux;
aux.elo = null;
ultimo = aux;
}
n++;
}
// ------------------------------- consultarListaEsquerda
public int consultarListaEsquerda ()
{
Nodo aux;
int dado;
aux = primeiro;
if (aux != null) {
return(primeiro.dado);
} else
return(0);
}
// ------------------------------- consultarListaDireita
public int consultarListaDireita ()
{
Nodo aux;
aux = ultimo;
if (aux != null) {
return(ultimo.dado);
} else
return(0);
}
// ------------------------------- imprimirLista
public void imprimirLista ()
{
Nodo aux;
aux = primeiro;
66
Console.Write ("Lista Encadeada Simples: ");
if (aux != null) {
while (aux != null) {
Console.Write (aux.dado + " ");
aux = aux.elo;
}
} else {
Console.Write ("Vazia");
}
Console.WriteLine ();
}
}
}
using System;
namespace Dados17
{
class MainClass
{
public static void Main (string[] args)
{
ListaEncadeadaDescritor lista = new ListaEncadeadaDescritor ();
char op, ch = 'e';
int dado = 0;
do {
Console.Write ("[I]ncluir, [C]onsultar ou [F]im: ");
do {
String s = Console.ReadLine ();
s = s.ToLower ();
op = s [0];
} while (op != 'i' && op != 'c' && op != 'f');
if (op == 'i' || op == 'c') {
do {
Console.Write ("[E]squerda ou [D]ireita: ");
String s = Console.ReadLine ();
s = s.ToLower ();
ch = s [0];
} while (ch != 'e' && ch != 'd');
}
switch (op) {
case 'i':
Console.Write ("Dado: ");
String s = Console.ReadLine ();
dado = Convert.ToInt32 (s);
if (dado != 0) {
if (ch == 'e') {
lista.inserirListaEsquerda (dado);
} else {
lista.inserirListaDireita (dado);
}
}
break;
case 'c':
if (ch == 'e') {
dado = lista.consultarListaEsquerda ();
} else {
dado = lista.consultarListaDireita ();
}
Console.WriteLine ("Dado Consultado: " + dado);
break;
}
67
lista.imprimirLista ();
} while (op != 'f');
}
}
}
Resultado do Programa:
using System;
namespace Dados18
{
public class Nodo
{
public int dado;
public Nodo elo = null;
}
}
using System;
namespace Dados18
{
public class ListaEncadeadaDescritor
{
private Nodo primeiro;
private int n;
68
private Nodo ultimo;
// ------------------------------- construtor
public ListaEncadeadaDescritor ()
{
primeiro = null;
n = 0;
ultimo = null;
}
// ------------------------------- inserirListaEsquerda
public void inserirListaEsquerda (int valor)
{
Nodo aux = new Nodo ();
aux.dado = valor;
if (n == 0) {
primeiro = aux;
ultimo = aux;
aux.elo = null;
} else {
aux.elo = primeiro;
primeiro = aux;
}
n++;
}
// ------------------------------- inserirListaDireita
public void inserirListaDireita (int valor)
{
Nodo aux = new Nodo ();
Nodo tmp;
aux.dado = valor;
if (n == 0) {
primeiro = aux;
ultimo = aux;
} else {
tmp = ultimo;
tmp.elo = aux;
aux.elo = null;
ultimo = aux;
}
n++;
}
// ------------------------------- removerListaEsquerda
public int removerListaEsquerda ()
{
Nodo aux = primeiro;
int dado;
if (n == 0) {
return(0);
} else {
dado = aux.dado;
primeiro = aux.elo;
n--;
return(dado);
}
}
// ------------------------------- removerListaDireita
public int removerListaDireita ()
{
Nodo tmp, ant = primeiro, aux = ultimo;
int dado;
if (n == 0) {
return(0);
} else {
dado = aux.dado;
69
n--;
tmp = primeiro;
while (tmp.elo != null) {
ant = tmp;
tmp = tmp.elo;
}
ant.elo = null;
ultimo = ant;
return(dado);
}
}
// ------------------------------- consultarListaEsquerda
public int consultarListaEsquerda ()
{
Nodo aux;
aux = primeiro;
if (aux != null) {
return(primeiro.dado);
} else
return(0);
}
// ------------------------------- consultarListaDireita
public int consultarListaDireita ()
{
Nodo aux;
aux = ultimo;
if (aux != null) {
return(ultimo.dado);
} else
return(0);
}
// ------------------------------- imprimirLista
public void imprimirLista ()
{
Nodo aux;
aux = primeiro;
using System;
namespace Dados18
{
class MainClass
{
public static void Main (string[] args)
70
{
ListaEncadeadaDescritor lista = new ListaEncadeadaDescritor ();
char op, ch = 'e';
int dado = 0;
do {
Console.Write ("[I]ncluir, [C]onsultar, [R]emover ou [F]im: ");
do {
String s = Console.ReadLine ();
s = s.ToLower ();
op = s [0];
} while (op != 'i' && op != 'c' && op != 'r' && op != 'f');
if (op == 'i' || op == 'r' || op == 'c') {
do {
Console.Write ("[E]squerda ou [D]ireita: ");
String s = Console.ReadLine ();
s = s.ToLower ();
ch = s [0];
} while (ch != 'e' && ch != 'd');
}
switch (op) {
case 'i':
Console.Write ("Dado: ");
String s = Console.ReadLine ();
dado = Convert.ToInt32 (s);
if (dado != 0) {
if (ch == 'e') {
lista.inserirListaEsquerda (dado);
} else {
lista.inserirListaDireita (dado);
}
}
break;
case 'r':
if (ch == 'e') {
dado = lista.removerListaEsquerda ();
} else {
dado = lista.removerListaDireita ();
}
if (dado != 0) {
Console.WriteLine ("Nodo Removido: " + dado);
} else {
Console.WriteLine ("Status: Lista Vazia");
}
break;
case 'c':
if (ch == 'e') {
dado = lista.consultarListaEsquerda ();
} else {
dado = lista.consultarListaDireita ();
}
Console.WriteLine ("Dado Consultado: " + dado);
break;
}
lista.imprimirLista ();
} while (op != 'f');
}
}
}
Resultado do Programa:
71
[I]ncluir, [C]onsultar, [R]emover ou [F]im: i
[E]squerda ou [D]ireita: d
Dado: 20
Lista Encadeada Simples: 10 20
[I]ncluir, [C]onsultar, [R]emover ou [F]im: i
[E]squerda ou [D]ireita: d
Dado: 30
Lista Encadeada Simples: 10 20 30
[I]ncluir, [C]onsultar, [R]emover ou [F]im: c
[E]squerda ou [D]ireita: e
Dado Consultado: 10
Lista Encadeada Simples: 10 20 30
[I]ncluir, [C]onsultar, [R]emover ou [F]im: c
[E]squerda ou [D]ireita: d
Dado Consultado: 30
Lista Encadeada Simples: 10 20 30
[I]ncluir, [C]onsultar, [R]emover ou [F]im: r
[E]squerda ou [D]ireita: r
[E]squerda ou [D]ireita: e
Nodo Removido: 10
Lista Encadeada Simples: 20 30
[I]ncluir, [C]onsultar, [R]emover ou [F]im: r
[E]squerda ou [D]ireita: d
Nodo Removido: 30
Lista Encadeada Simples: 20
[I]ncluir, [C]onsultar, [R]emover ou [F]im: r
[E]squerda ou [D]ireita: e
Nodo Removido: 20
Lista Encadeada Simples: Vazia
[I]ncluir, [C]onsultar, [R]emover ou [F]im: r
[E]squerda ou [D]ireita: d
Status: Lista Vazia
Lista Encadeada Simples: Vazia
[I]ncluir, [C]onsultar, [R]emover ou [F]im: f
Lista Encadeada Simples: Vazia
72
Figura 10a: Lista Duplamente Encadeada
using System;
namespace Dados19
{
public class Nodo
{
public Nodo anterior = null;
public int dado;
public Nodo posterior = null;
}
}
using System;
namespace Dados19
{
public class ListaDuplamenteEncadeadaDescritor
{
private Nodo primeiro;
private int n;
private Nodo ultimo;
// ------------------------------- construtor
public ListaDuplamenteEncadeadaDescritor ()
{
primeiro = null;
n = 0;
ultimo = null;
}
// ------------------------------- inserirListaEsquerda
public void inserirListaEsquerda (int valor)
{
Nodo aux = new Nodo ();
aux.dado = valor;
if (n == 0) {
primeiro = aux;
ultimo = aux;
aux.anterior = null;
} else {
73
aux.anterior = primeiro;
primeiro = aux;
}
n++;
}
// ------------------------------- inserirListaDireita
public void inserirListaDireita (int valor)
{
Nodo aux = new Nodo ();
Nodo tmp;
aux.dado = valor;
if (n == 0) {
primeiro = aux;
ultimo = aux;
} else {
tmp = ultimo;
tmp.posterior = aux;
aux.anterior = tmp;
aux.posterior = null;
ultimo = aux;
}
n++;
}
// ------------------------------- removerListaEsquerda
public int removerListaEsquerda ()
{
Nodo aux = primeiro;
int dado;
if (n == 0) {
return(0);
} else {
dado = aux.dado;
n--;
if (n == 0) {
primeiro = null;
ultimo = null;
} else {
primeiro = aux.posterior;
primeiro.anterior = null;
}
return(dado);
}
}
// ------------------------------- removerListaDireita
public int removerListaDireita ()
{
Nodo ant, aux = ultimo;
int dado;
if (n == 0) {
return(0);
} else {
dado = aux.dado;
n--;
if (n == 0) {
primeiro = null;
ultimo = null;
} else {
ant = aux.anterior;
ultimo = ant;
ant.posterior = null;
}
return(dado);
}
}
74
// ------------------------------- consultarListaEsquerda
public int consultarListaEsquerda ()
{
Nodo aux;
aux = primeiro;
if (aux != null) {
return(primeiro.dado);
} else
return(0);
}
// ------------------------------- consultarListaDireita
public int consultarListaDireita ()
{
Nodo aux;
aux = ultimo;
if (aux != null) {
return(ultimo.dado);
} else
return(0);
}
// ------------------------------- imprimirLista
public void imprimirLista ()
{
Nodo aux = primeiro;
using System;
namespace Dados19
{
class MainClass
{
public static void Main (string[] args)
{
ListaDuplamenteEncadeadaDescritor lista = new ListaDuplamenteEncadeadaDescritor();
char op, ch = 'e';
int dado = 0;
do {
Console.Write ("[I]ncluir, [C]onsultar, [R]emover ou [F]im: ");
do {
String s = Console.ReadLine();
s = s.ToLower();
op = s[0];
} while (op != 'i' && op != 'c' && op != 'r' && op != 'f');
if (op == 'i' || op == 'r' || op == 'c') {
75
do {
Console.Write ("[E]squerda ou [D]ireita: ");
String s = Console.ReadLine();
s = s.ToLower();
ch = s[0];
} while (ch != 'e' && ch != 'd');
}
switch (op) {
case 'i': Console.Write ("Dado: ");
String s = Console.ReadLine();
dado = Convert.ToInt32(s);
if (dado != 0) {
if (ch == 'e') {
lista.inserirListaEsquerda(dado);
}
else {
lista.inserirListaDireita(dado);
}
}
break;
case 'r': if (ch == 'e') {
dado = lista.removerListaEsquerda();
}
else {
dado = lista.removerListaDireita();
}
if (dado != 0) {
Console.WriteLine ("Nodo Removido: " + dado);
}
else {
Console.WriteLine ("Status: Lista Vazia");
}
break;
case 'c': if (ch == 'e') {
dado = lista.consultarListaEsquerda();
}
else {
dado = lista.consultarListaDireita();
}
Console.WriteLine ("Dado Consultado: " + dado);
break;
}
lista.imprimirLista();
} while (op != 'f');
}
}
}
Resultado do Programa:
76
[E]squerda ou [D]ireita: d
Dado Consultado: 30
Lista Duplamente Encadeada: 10 20 30
[I]ncluir, [C]onsultar, [R]emover ou [F]im: r
[E]squerda ou [D]ireita: r
[E]squerda ou [D]ireita: e
Nodo Removido: 10
Lista Duplamente Encadeada: 20 30
[I]ncluir, [C]onsultar, [R]emover ou [F]im: r
[E]squerda ou [D]ireita: d
Nodo Removido: 30
Lista Duplamente Encadeada: 20
[I]ncluir, [C]onsultar, [R]emover ou [F]im: r
[E]squerda ou [D]ireita: d
Nodo Removido: 20
Lista Duplamente Encadeada: Vazia
[I]ncluir, [C]onsultar, [R]emover ou [F]im:
77
a) Preencha os campos de elo com os valores adequados para
que seja representada a seqüência (A, B, C, D): (sem
descritor)
78
Vantagens e Desvantagens das Listas Duplamente Encadeadas
Vantagens
Desvantagens
3.2.5.1 Filas
Início Fim
Critério de Utilização
79
Figura 12: Fila Circular
using System;
namespace Dados20
{
class MainClass
{
public static void Main (string[] args)
{
Fila fila = new Fila(7);
int valor;
int erro = 0;
char ch;
do {
Console.Write ("[I]ncluir, [E]xcluir, [C]onsultar ou [F]im? ");
do {
String s = Console.ReadLine();
s = s.ToLower();
80
ch = s[0];
} while (ch != 'i' && ch != 'e' && ch != 'c' && ch != 'f');
switch (ch)
{
case 'i': Console.Write ("Valor: ");
String s = Console.ReadLine();
valor = Convert.ToInt32(s);
erro = fila.insereFila(valor);
break;
case 'e': valor = fila.excluiFila();
break;
case 'c': valor = fila.consultaFila();
if (valor != 0) {
Console.WriteLine ("Primeiro da Fila: " + valor);
}
else {
Console.WriteLine ("ERRO: Fila Vazia");
}
break;
}
fila.exibeFila();
if (erro != 0)
fila.imprimeErro(erro);
} while (ch != 'f');
}
}
}
using System;
namespace Dados20
{
public class Fila
{
const int SUCESSO = 0;
const int FILA_CHEIA = 1;
const int FILA_VAZIA = 2;
private int primeiro;
private int ultimo;
private int []elem;
// ------------------------------------ Construtor
// ------------------------------------ insereFila
if (ultimo == m - 1) {
return(FILA_CHEIA);
}
else {
ultimo++;
elem[ultimo] = dado;
return(SUCESSO);
}
}
// -------------------------------- excluiFila
81
public int excluiFila() {
if (ultimo == -1) {
return(FILA_VAZIA);
}
else {
Console.WriteLine ("Dado Excluido: " + elem[primeiro]);
primeiro++;
if (primeiro > ultimo) {
primeiro = 0;
ultimo = -1;
}
return(SUCESSO);
}
}
// ------------------------------- consultaFila
// ------------------------------- exibeFila
// ------------------------------------------ imprimeErroCircular
Resultado do Programa:
82
Fila: 20 30
[I]ncluir, [E]xcluir, [C]onsultar ou [F]im? e
Dado Excluido: 20
Fila: 30
[I]ncluir, [E]xcluir, [C]onsultar ou [F]im? e
Dado Excluido: 30
Fila: [I]ncluir, [E]xcluir, [C]onsultar ou [F]im? c
ERRO: Fila Vazia
Fila: [I]ncluir, [E]xcluir, [C]onsultar ou [F]im?
Inclusão de: 3, 5, 4, 7, 8 e 6
83
Figura 13: Fila Circular em um vetor
using System;
namespace Dados21
{
class MainClass
{
public static void Main (string[] args)
{
FilaCircular fila = new FilaCircular (7);
int elemento = 0;
char op;
do {
fila.exibeFilaCircular ();
do {
Console.Write ("[I]nsere, [R]emove, [C]onsulta ou [F]im: ");
string s = Console.ReadLine ();
s = s.ToLower ();
op = s [0];
} while (!StrChr ("IiRrCcFf", op));
switch (op) { // int ou char
case 'I':
case 'i':
Console.Write ("Elemento: ");
string s = Console.ReadLine ();
elemento = Convert.ToInt32 (s);
fila.insereFilaCircular (elemento);
break;
case 'R':
case 'r':
elemento = fila.removeFilaCircular ();
if (elemento != -1) {
Console.WriteLine ("Primeiro Elemento da Fila: " + elemento);
}
break;
case 'C':
case 'c':
elemento = fila.consultaFilaCircular ();
if (elemento != -1) {
Console.WriteLine ("Primeiro Elemento da Fila: " + elemento);
}
break;
}
} while (op != 'F' && op != 'f');
}
// ------------------------------------------- StrChr
static bool StrChr (string s, char ch)
{
int n = s.Length;
for (int i = 0; i < n; i++) {
if (s [i] == ch) {
return(true);
84
}
}
return(false);
}
}
}
using System;
namespace Dados21
{
public class FilaCircular
{
private int[] v;
private int primeiro;
private int ultimo;
private int n;
// ---------------------------- construtor
public FilaCircular (int numElementos)
{
v = new int[numElementos];
primeiro = 0;
ultimo = -1;
n = 0;
}
// ---------------------------- insereFilaCircular
public void insereFilaCircular (int elemento)
{
int m = v.Length;
if (n < m) {
ultimo = (ultimo + 1) % m;
v [ultimo] = elemento;
n++;
} else {
Console.WriteLine ("Status: Fila Circular Cheia");
}
}
// ---------------------------- removeFilaCircular
public int removeFilaCircular ()
{
int m = v.Length;
int elemento;
if (n != 0) {
elemento = v [primeiro];
primeiro = (primeiro + 1) % m;
n--; // Guilherme Tomaschewski Netto
if (n == 0) { // Guilherme Tomaschewski Netto
// if (primeiro > ultimo) { // Guilherme Tomaschewski Netto
primeiro = 0;
ultimo = -1;
}
// n--; // Guilherme Tomaschewski Netto
return(elemento);
} else {
Console.WriteLine ("Status: Fila Circular Vazia");
return(-1);
}
}
// ---------------------------- consultaFilaCircular
public int consultaFilaCircular ()
{
int m = v.Length;
int elemento;
85
if (ultimo != -1) {
int prim = (primeiro + 1) % m;
elemento = v [prim];
return(elemento);
} else {
Console.WriteLine ("Status: Fila Circular Vazia");
return(-1);
}
}
// ---------------------------- exibeFilaCircular
public void exibeFilaCircular ()
{
int m = v.Length;
int t = primeiro;
Console.Write ("Fila Circular: ");
for (int i = 1; i <= n; i++) {
Console.Write (v [t] + "(" + t + ") ");
t = (t + 1) % m;
}
if (ultimo == -1) {
Console.Write ("Vazia");
}
Console.WriteLine ();
}
}
}
Resultado do Programa:
ultimo = (ultimo + 1) % m;
// onde m é número máximo de elementos do vetor
86
Figura 14: Cálculo da nova Posição na Fila Circular
using System;
namespace Dados21a
{
class MainClass
{
public static void Main (string[] args)
{
Fila fila = new Fila(7);
int elemento = 0;
char op;
do {
fila.exibeFila();
do {
Console.Write ("[I]nsere, [R]emove, [C]onsulta ou [F]im: ");
String s = Console.ReadLine();
op = s[0];
} while (!StrChr("IiRrCcFf", op));
switch (op) { // int ou char
case 'I':
case 'i': Console.Write ("Elemento: ");
string s = Console.ReadLine();
elemento = Convert.ToInt32(s);
fila.insereFila(elemento);
break;
case 'R':
case 'r': elemento = fila.removeFila();
if (elemento != -1) {
Console.WriteLine ("Primeiro Elemento da Fila: " + elemento);
}
break;
case 'C':
case 'c': elemento = fila.consultaFila();
if (elemento != -1) {
Console.WriteLine ("Primeiro Elemento da Fila: " + elemento);
}
87
break;
}
} while (op != 'F' && op != 'f');
}
// ------------------------------------------- StrChr
static bool StrChr (string s, char ch)
{
int n = s.Length;
for (int i = 0; i < n; i++) {
if (s [i] == ch) {
return(true);
}
}
return(false);
}
}
}
using System;
namespace Dados21a
{
public class Fila
{
private int [] v;
private int primeiro;
private int ultimo;
private int n;
// ---------------------------- construtor
// ---------------------------- insereFila
// ---------------------------- removeFila
if (ultimo != -1) {
88
elemento = v[primeiro];
primeiro++;
n--;
if (n == 0) {
primeiro = 0;
ultimo = -1;
}
return(elemento);
} else {
Console.WriteLine ("Status: Fila Vazia");
return(-1);
}
}
// ---------------------------- consultaFila
if (ultimo != -1) {
elemento = v[primeiro];
return(elemento);
} else {
Console.WriteLine ("Status: Fila Vazia");
return(-1);
}
}
// ---------------------------- exibeFila
// ---------------------------- deslocaFila
Resultado do Programa:
Fila: Vazia
Fila: 10(0)
Fila: 10(0) 20(1)
Fila: 10(0) 20(1) 30(2)
Primeiro Elemento da Fila: 10
Fila: 10(0) 20(1) 30(2)
89
Primeiro Elemento da Fila: 10
Fila: 20(1) 30(2)
Primeiro Elemento da Fila: 20
Fila: 30(2)
Primeiro Elemento da Fila: 30
Fila: Vazia
using System;
namespace Dados22
{
public class Nodo
{
public int dado;
public Nodo elo;
}
}
using System;
namespace Dados22
{
public class FilaDinamica
{
private Nodo primeiro;
private int tamanho;
90
private Nodo ultimo;
// ---------------------------------------------- Construtor
public FilaDinamica ()
{
primeiro = null;
tamanho = 0;
ultimo = null;
}
// ---------------------------------------------- inserirFilaDinamica
public void inserirFilaDinamica (int dado)
{
Nodo t = new Nodo ();
t.dado = dado;
t.elo = null;
tamanho = tamanho + 1;
if (ultimo != null) {
ultimo.elo = t;
}
ultimo = t;
if (primeiro == null) {
primeiro = t;
}
}
// ---------------------------------------------- excluirFilaDinamica
public int excluirFilaDinamica ()
{
Nodo t;
int dado;
if (primeiro == null) {
return(-1);
} else {
t = primeiro;
dado = t.dado;
tamanho = tamanho - 1;
primeiro = t.elo;
if (primeiro == null) {
ultimo = null;
return(-1);
}
return(dado);
}
}
// ---------------------------------------------- consultarFilaDinalica
public int consultarFilaDinamica ()
{
if (primeiro == null) {
return(-1);
} else {
return(primeiro.dado);
}
}
// ---------------------------------------------- exibirFilaDinalica
public void exibirFilaDinamica ()
{
Nodo t = primeiro;
91
Console.WriteLine ();
}
}
}
using System;
namespace Dados22
{
class MainClass
{
public static void Main (string[] args)
{
FilaDinamica fila = new FilaDinamica ();
int valor, dado;
char tecla;
do {
fila.exibirFilaDinamica ();
Console.Write ("[I]ncluir, [E]xcluir, [C]onsultar ou [F]im? ");
do {
String s = Console.ReadLine ();
s = s.ToLower ();
tecla = s [0];
} while (tecla != 'i' && tecla != 'e' && tecla != 'c' && tecla != 'f');
switch (tecla) {
case 'i':
Console.Write ("Elemento: ");
String s = Console.ReadLine ();
valor = Convert.ToInt32 (s);
fila.inserirFilaDinamica (valor);
break;
case 'e':
dado = fila.excluirFilaDinamica ();
if (dado != -1) {
Console.WriteLine ("Elemento Excluído: " + dado);
}
break;
case 'c':
dado = fila.consultarFilaDinamica ();
if (dado != -1) {
Console.WriteLine ("Elemento Consultado: " + dado);
}
break;
}
} while (tecla != 'f');
}
}
}
Resultado do Programa:
92
Elemento Excluído: 10
Fila Dinamica: 20 30
[I]ncluir, [E]xcluir, [C]onsultar ou [F]im? e
Elemento Excluído: 20
Fila Dinamica: 30
[I]ncluir, [E]xcluir, [C]onsultar ou [F]im? e
Fila Dinamica: Vazia
[I]ncluir, [E]xcluir, [C]onsultar ou [F]im? f
3.2.5.2 Pilhas
Critério de Utilização
Identificadores da Pilha
93
Figura 17: Pilha em um Vetor
using System;
namespace Dados23
{
class MainClass
{
public static void Main (string[] args)
{
PilhaVetor pilha = new PilhaVetor (7);
int valor;
int erro = 0;
char ch;
do {
Console.Write ("[P]ush, P[o]p, [C]onsultar ou [F]im? ");
do {
String s = Console.ReadLine ();
s = s.ToLower ();
ch = s [0];
} while (ch != 'p' && ch != 'o' && ch != 'c' && ch != 'f');
switch (ch) {
case 'p':
Console.Write ("Elemento: ");
String s = Console.ReadLine ();
valor = Convert.ToInt32 (s);
erro = pilha.push (valor);
break;
case 'o':
erro = pilha.pop ();
break;
case 'c':
erro = pilha.consultaPilha ();
break;
}
pilha.exibePilha ();
if (erro != 0) {
pilha.imprimeErro (erro);
}
} while (ch != 'f');
}
}
}
94
// ------------------------------------------------------- Fonte: Dados23.cs
using System;
namespace Dados23
{
public class PilhaVetor
{
const int SUCESSO = 0;
const int PILHA_CHEIA = 1;
const int PILHA_VAZIA = 2;
private int topo;
private int []elem;
private int m;
// ------------------------------------ construtor
// ------------------------------------ push
// -------------------------------- pop
// ------------------------------- consultaPilha
// ------------------------------- exibePilha
95
for (int i = topo;i >= 0; i--) {
Console.Write (elem[i] + " ");
}
Console.WriteLine ();
}
}
// ------------------------------------------ imprimeErro
Resultado do Programa:
using System;
namespace Dados23a
{
class MainClass
{
public static void Main (string[] args)
{
Pilha pilha = new Pilha (6);
int valor;
pilha.Push (10);
pilha.Exibe ();
pilha.Push (20);
96
pilha.Exibe ();
pilha.Push (30);
pilha.Exibe ();
pilha.Push (40);
pilha.Exibe ();
pilha.Push (50);
pilha.Exibe ();
pilha.Push (60);
pilha.Exibe ();
// -------------------------------------------------- Pilha.cs
using System;
namespace Dados23a
{
public class Pilha
{
private int [] vet;
private int topo;
// --------------------------------- construtor
// --------------------------------- Push
97
// --------------------------------- Pop
if (topo >= 0) {
valor = vet[topo];
topo--;
return(valor);
}
else {
Console.WriteLine ("Status: Pilha Vazia");
return(-1);
}
}
// --------------------------------- exibePilha
Resultado do Programa:
Pilha: [10]
Pilha: [10,20]
Pilha: [10,20,30]
Pilha: [10,20,30,40]
Pilha: [10,20,30,40,50]
Pilha: [10,20,30,40,50,60]
Valor: 60
Pilha: [10,20,30,40,50]
Valor: 50
Pilha: [10,20,30,40]
Valor: 40
Pilha: [10,20,30]
Valor: 30
Pilha: [10,20]
Valor: 20
Pilha: [10]
Valor: 10
Pilha: []
Status: Pilha Vazia
Pilha: []
98
Figura 18: Pilha em uma Lista Encadeada
using System;
namespace Dados24
{
public class Nodo
{
public int dado;
public Nodo elo = null;
}
}
// --------------------------------------------------- PilhaDinamica.cs
using System;
namespace Dados24
{
public class PilhaDinamica
{
private Nodo topo;
// ---------------------------------------------- construtor
public PilhaDinamica ()
{
topo = null;
}
// ---------------------------------------------- push
public void push (int dado)
{
Nodo t = new Nodo ();
t.dado = dado;
t.elo = topo;
topo = t;
}
// ---------------------------------------------- pop
public int pop ()
{
Nodo t;
99
if (topo == null) {
return(-1);
} else {
t = topo;
topo = t.elo;
return(t.dado);
}
}
// ---------------------------------------------- consultaPilha
public int consultaPilha ()
{
Nodo t;
if (topo == null) {
return(-1);
} else {
t = topo;
return(t.dado);
}
}
// ------------------------------------------------- exibePilha
public void exibePilha ()
{
Nodo t;
using System;
namespace Dados24
{
class MainClass
{
public static void Main (string[] args)
{
PilhaDinamica pilha = new PilhaDinamica ();
int valor, dado;
char tecla;
do {
pilha.exibePilha ();
Console.Write ("[P]ush, p[O]p, [C]onsultar ou [F]im? ");
do {
String s = Console.ReadLine ();
s = s.ToLower ();
tecla = s [0];
} while (tecla != 'p' && tecla != 'o' && tecla != 'c' && tecla != 'f');
switch (tecla) {
case 'p':
Console.Write ("Elemento a ser Empilhado: ");
String s = Console.ReadLine ();
100
valor = Convert.ToInt32 (s);
pilha.push (valor);
break;
case 'o':
dado = pilha.pop ();
Console.WriteLine ("Dado: " + dado);
break;
case 'c':
dado = pilha.consultaPilha ();
Console.WriteLine ("Dado: " + dado);
break;
}
} while (tecla != 'f');
}
}
}
Resultado do Programa:
Pilha: Vazia
[P]ush, p[O]p, [C]onsultar ou [F]im? p
Elemento a ser Empilhado: 10
Pilha: 10
[P]ush, p[O]p, [C]onsultar ou [F]im? p
Elemento a ser Empilhado: 20
Pilha: 20 10
[P]ush, p[O]p, [C]onsultar ou [F]im? p
Elemento a ser Empilhado: 30
Pilha: 30 20 10
[P]ush, p[O]p, [C]onsultar ou [F]im? c
Dado: 30
Pilha: 30 20 10
[P]ush, p[O]p, [C]onsultar ou [F]im? o
Dado: 30
Pilha: 20 10
[P]ush, p[O]p, [C]onsultar ou [F]im? o
Dado: 20
Pilha: 10
[P]ush, p[O]p, [C]onsultar ou [F]im? o
Dado: 10
Pilha: Vazia
[P]ush, p[O]p, [C]onsultar ou [F]im? f
Início
Fim
Figura 19: Deque
101
A retirada só pode ser efetuada ou no início ou no final da lista.
Deque Vazio
Esq = -1
Dir = -1
Deque Cheio
Esq = 0
Dir = m-1
using System;
namespace Dados26
{
class MainClass
{
public static void Main (string[] args)
{
Deque deque = new Deque (7);
102
int valor;
char ch, op;
int erro = 0;
do {
deque.exibeDeque ();
Console.Write ("[I]nclui, [E]xclui, [C]onsulta ou [F]im: ");
do {
String s = Console.ReadLine ();
s = s.ToLower ();
op = s [0];
} while (op != 'i' && op != 'e' && op != 'c' && op != 'f');
if (op == 'i' || op == 'e' || op == 'c') {
Console.Write ("[E]squerda ou [D]ireita: ");
do {
String s = Console.ReadLine ();
s = s.ToLower ();
ch = s [0];
} while (ch != 'e' && ch != 'd');
switch (op) {
case 'i':
Console.Write ("Elemento: ");
String s = Console.ReadLine ();
valor = Convert.ToInt32 (s);
if (valor != 0) {
switch (ch) {
case 'e':
erro = deque.incluiDequeEsquerda (valor);
break;
case 'd':
erro = deque.incluiDequeDireita (valor);
break;
}
}
break;
case 'e':
switch (ch) {
case 'e':
erro = deque.excluiDequeEsquerda ();
break;
case 'd':
erro = deque.excluiDequeDireita ();
break;
}
break;
case 'c':
switch (ch) {
case 'e':
erro = deque.consultaDequeEsquerda ();
break;
case 'd':
erro = deque.consultaDequeDireita ();
break;
}
break;
}
if (erro != 0) {
deque.imprimeErro (erro);
}
}
} while (op != 'f');
}
}
}
// -------------------------------------------------------------------- Deque.cs
103
using System;
namespace Dados26
{
public class Deque
{
const int SUCESSO = 0;
const int DEQUE_ESQUERDO_CHEIO = 1;
const int DEQUE_DIREITO_CHEIO = 2;
const int DEQUE_VAZIO = 3;
private int esq;
private int dir;
private int[] v;
private int m;
// ------------------------------------ construtor
public Deque (int numElementos)
{
v = new int[numElementos];
m = numElementos;
esq = -1;
dir = -1;
}
// ------------------------------------ incluiDequeEsquerda
public int incluiDequeEsquerda (int dado)
{
if (esq == 0) {
return(DEQUE_ESQUERDO_CHEIO);
} else {
if (esq == -1) {
esq = m / 2;
dir = esq;
} else {
esq = esq - 1;
}
v [esq] = dado;
return(SUCESSO);
}
}
// ------------------------------------ incluiDequeDireita
public int incluiDequeDireita (int dado)
{
if (dir == m - 1) {
return(DEQUE_DIREITO_CHEIO);
} else {
if (dir == -1) {
dir = m / 2;
esq = dir;
} else {
dir = dir + 1;
}
v [dir] = dado;
return(SUCESSO);
}
}
// ------------------------------------ excluiDequeEsquerda
public int excluiDequeEsquerda ()
{
if (esq == -1) {
return(DEQUE_VAZIO);
} else {
Console.WriteLine ("Dado Removido a Esquerda: " + v [esq]);
esq = esq + 1;
if (esq > dir) {
esq = -1;
dir = -1;
}
return(SUCESSO);
104
}
}
// ------------------------------------ excluiDequeDireita
public int excluiDequeDireita ()
{
if (dir == -1) {
return(DEQUE_VAZIO);
} else {
Console.WriteLine ("Dado excluido Direita do Deque:" + v [dir]);
dir = dir - 1;
if (dir < esq) {
esq = -1;
dir = -1;
}
return(SUCESSO);
}
}
// ------------------------------------ consultaDequeEsquerda
public int consultaDequeEsquerda ()
{
if (esq == -1) {
return(DEQUE_VAZIO);
} else {
Console.WriteLine ("Valor Consultado Esquerda Deque: " + v [esq]);
return(SUCESSO);
}
}
// ------------------------------------ ConsultaDequeDireita
public int consultaDequeDireita ()
{
if (dir == -1) {
return(DEQUE_VAZIO);
} else {
Console.WriteLine ("Valor Consultado Direita Deque: " + v [dir]);
return(SUCESSO);
}
}
// ------------------------------------ exibeDeque
public void exibeDeque ()
{
Console.Write ("Deque: ");
if (esq == -1) {
Console.Write ("Vazio");
} else {
for (int i = esq; i <= dir; i++) {
Console.Write (v [i] + " ");
}
}
Console.WriteLine ();
}
// ------------------------------------ Imprime_Erro
public void imprimeErro (int erro)
{
switch (erro) {
case DEQUE_ESQUERDO_CHEIO:
Console.WriteLine ("ERRO: Deque Cheio à Esquerda");
break;
case DEQUE_DIREITO_CHEIO:
Console.WriteLine ("ERRO: Deque Cheio à Direita");
break;
case DEQUE_VAZIO:
Console.WriteLine ("ERRO: Deque Vazio");
break;
}
}
}
}
105
Resultado do Programa:
Deque: Vazio
[I]nclui, [E]xclui, [C]onsulta ou [F]im: i
[E]squerda ou [D]ireita: e
Elemento: 10
Deque: 10
[I]nclui, [E]xclui, [C]onsulta ou [F]im: i
[E]squerda ou [D]ireita: d
Elemento: 20
Deque: 10 20
[I]nclui, [E]xclui, [C]onsulta ou [F]im: i
[E]squerda ou [D]ireita: d
Elemento: 30
Deque: 10 20 30
[I]nclui, [E]xclui, [C]onsulta ou [F]im: c
[E]squerda ou [D]ireita: e
Valor Consultado Esquerda Deque: 10
Deque: 10 20 30
[I]nclui, [E]xclui, [C]onsulta ou [F]im: c
[E]squerda ou [D]ireita: d
Valor Consultado Direita Deque: 30
Deque: 10 20 30
[I]nclui, [E]xclui, [C]onsulta ou [F]im:
106
4. Pesquisa de Dados
107
Problema: Escreva um programa em C# que faz uma Busca
Seqüencial em uma estrutura que possui os campos: chave,
nome, altura e peso.
using System;
namespace Dados27
{
class MainClass
{
public static void Main (string[] args)
{
Tabela tabela = new Tabela (10);
int key, chave;
tabela.entradaTabela ();
do {
Console.Write ("Chave para consulta [0 - Sair]: ");
String s = Console.ReadLine ();
key = Convert.ToInt32 (s);
if (key != 0) {
chave = tabela.pesquisaSequencial (key);
tabela.exibeTabela (chave);
}
} while (key != 0);
}
}
}
using System;
namespace Dados27
{
public class Tabela
{
private int [] chave;
private String [] nome;
private double [] peso;
private double [] altura;
private int n = -1;
private int max;
// ---------------------------------------------- construtor
// ---------------------------------------------- pesquisaSequencial
108
for (int i = 0;i <= n;i++) {
if (chave[i] == ch) {
key = i;
break;
}
}
return(key);
}
// ---------------------------------------------- exibeTabela
// ---------------------------------------------- entradaTabela
do {
n++;
Console.Write ("Chave: ");
s = Console.ReadLine();
chave[n] = Convert.ToInt32(s);
if (chave[n] == 0) {
Environment.Exit(0);
}
Console.Write ("Nome: ");
nome[n] = Console.ReadLine();
Console.Write ("Peso: ");
s = Console.ReadLine();
peso[n] = Convert.ToInt32(s);
Console.Write ("Altura: ");
s = Console.ReadLine();
altura[n] = Convert.ToDouble(s);
Console.Write ("Continua [S/N] ?");
do {
s = Console.ReadLine();
s = s.ToLower();
tecla = s[0];
} while (tecla != 's' && tecla != 'n');
} while (tecla == 's' && n < max);
}
}
}
Resultado do Programa:
Chave: 10
Nome: Paulo
Peso: 94
Altura: 1.67
Continua [S/N] ?s
Chave: 20
Nome: Renato
Peso: 78
Altura: 1.80
109
Continua [S/N] ?n
Chave para consulta [0 - Sair]: 10
Chave: 10
Nome: Paulo
Peso: 94.0
Altura: 1.67
Chave para consulta [0 - Sair]: 20
Chave: 20
Nome: Renato
Peso: 78.0
Altura: 1.8
Chave para consulta [0 - Sair]: 30
Erro: Chave Inexistente
Chave para consulta [0 - Sair]: 0
using System;
namespace Dados28
{
class MainClass
{
public static void Main (string[] args)
{
Tabela tabela = new Tabela (10);
int key, chave;
tabela.entradaTabela ();
tabela.ordenaTabela ();
do {
Console.Write ("Chave para consulta [0 - Sair]: ");
String s = Console.ReadLine ();
key = Convert.ToInt32 (s);
if (key != 0) {
chave = tabela.pesquisaSequencial (key);
tabela.exibeTabela (chave);
}
} while (key != 0);
}
}
}
using System;
namespace Dados28
{
public class Tabela
{
private int max;
110
private int[] chave;
private String[] nome;
private double[] peso;
private double[] altura;
private int n;
// ---------------------------------------------- construtor
public Tabela (int numElementos)
{
max = numElementos;
chave = new int[max];
nome = new String[max];
peso = new double[max];
altura = new double[max];
n = -1;
}
// ---------------------------------------------- pesquisaSequencial
public int pesquisaSequencial (int ch)
{
int key = -1;
111
do {
n++;
Console.Write ("Chave: ");
string s = Console.ReadLine ();
chave [n] = Convert.ToInt32 (s);
if (chave [n] == 0) {
Environment.Exit (0);
}
Console.Write ("Nome: ");
nome [n] = Console.ReadLine ();
Console.Write ("Peso: ");
s = Console.ReadLine ();
peso [n] = Convert.ToInt32 (s);
Console.Write ("Altura: ");
s = Console.ReadLine ();
altura [n] = Convert.ToDouble (s);
Console.Write ("Continua [S/N] ?");
do {
s = Console.ReadLine ();
s = s.ToLower ();
tecla = s [0];
} while (tecla != 's' && tecla != 'n');
} while (tecla == 's' && n < max);
}
}
}
Resultado do Programa:
Chave: 10
Nome: Paulo
Peso: 94
Altura: 1.67
Continua [S/N] ?s
Chave: 20
Nome: Renato
Peso: 78
Altura: 1.80
Continua [S/N] ?n
Chave para consulta [0 - Sair]: 10
Chave: 10
Nome: Paulo
Peso: 94.0
Altura: 1.67
Chave para consulta [0 - Sair]: 20
Chave: 20
Nome: Renato
Peso: 78.0
Altura: 1.8
Chave para consulta [0 - Sair]: 0
112
Figura 23: Pesquisa Binária
nc = log n + 1
2
using System;
namespace Dados29
{
class MainClass
{
public static void Main (string[] args)
{
Tabela tabela = new Tabela (10);
int key, chave;
tabela.entradaTabela ();
113
tabela.ordenaTabela ();
do {
Console.Write ("Chave para consulta [0 - Sair]: ");
String s = Console.ReadLine ();
key = Convert.ToInt32 (s);
if (key != 0) {
chave = tabela.pesquisaBinaria (key);
tabela.exibeTabela (chave);
}
} while (key != 0);
}
}
}
using System;
namespace Dados29
{
public class Tabela
{
private int max;
private int[] chave;
private String[] nome;
private double[] peso;
private double[] altura;
private int n;
// ---------------------------------------------- construtor
public Tabela (int numElementos)
{
max = numElementos;
chave = new int[max];
nome = new String[max];
peso = new double[max];
altura = new double[max];
n = -1;
}
// ---------------------------------------------- pesquisaBinaria
public int pesquisaBinaria (int valor)
{
int indice = -1;
int inic, fim, metade;
inic = 0;
fim = (n - 1) + 1;
metade = n / 2;
do {
if (valor == chave [metade]) {
indice = metade;
break;
} else {
if (valor < chave [metade]) {
fim = metade - 1;
metade = (fim + inic) / 2;
} else {
inic = metade + 1;
metade = (fim + inic) / 2;
}
}
} while (indice == -1 && inic <= fim);
return(indice);
}
// ---------------------------------------------- ordenaTabela
public void ordenaTabela ()
{
for (int i = 0; i < n; i++) {
114
for (int j = i + 1; j <= n; j++) {
if (chave [i] > chave [j]) {
int temp = chave [i];
chave [i] = chave [j];
chave [j] = temp;
String s = nome [i];
nome [i] = nome [j];
nome [j] = s;
double f = peso [i];
peso [i] = peso [j];
peso [j] = f;
f = altura [i];
altura [i] = altura [j];
altura [j] = f;
}
}
}
}
// ---------------------------------------------- exibeTabela
public void exibeTabela (int key)
{
if (key != -1) {
Console.WriteLine ("Chave: " + chave [key]);
Console.WriteLine ("Nome: " + nome [key]);
Console.WriteLine ("Peso: " + peso [key]);
Console.WriteLine ("Altura: " + altura [key]);
} else {
Console.WriteLine ("Erro: Chave Inexistente");
}
}
// ---------------------------------------------- entradaTabela
public void entradaTabela ()
{
String s;
char tecla;
do {
n++;
Console.Write ("Chave: ");
s = Console.ReadLine ();
chave [n] = Convert.ToInt32 (s);
if (chave [n] == 0) {
Environment.Exit (0);
}
Console.Write ("Nome: ");
nome [n] = Console.ReadLine ();
Console.Write ("Peso: ");
s = Console.ReadLine ();
peso [n] = Convert.ToInt32 (s);
Console.Write ("Altura: ");
s = Console.ReadLine ();
altura [n] = Convert.ToDouble (s);
Console.Write ("Continua [S/N] ?");
do {
s = Console.ReadLine ();
s = s.ToLower ();
tecla = s [0];
} while (tecla != 's' && tecla != 'n');
} while (tecla == 's' && n < max);
}
}
}
Resultado do Programa:
Chave: 20
Nome: Beatriz
115
Peso: 56
Altura: 1.45
Continua [S/N] ?s
Chave: 30
Nome: Ana
Peso: 67
Altura: 1.56
Continua [S/N] ?s
Chave: 10
Nome: Carla
Peso: 78
Altura: 1.58
Continua [S/N] ?n
Chave para consulta [0 - Sair]: 10
Chave: 10
Nome: Carla
Peso: 78.0
Altura: 1.58
Chave para consulta [0 - Sair]: 20
Chave: 20
Nome: Beatriz
Peso: 56.0
Altura: 1.45
Chave para consulta [0 - Sair]: 30
Chave: 30
Nome: Ana
Peso: 67.0
Altura: 1.56
Chave para consulta [0 - Sair]: 0
Exemplo:
n = 53
entrada: [0..1000]
116
Note que no cálculo dos endereços houve repetições, tais
como: 2, 33, 23, 10 e 50, por causa disto, é necessário
verificar se o endereço está ocupado ou não. Finalmente os
endereços calculados são:
using System;
namespace Dados30
{
class MainClass
{
public static void Main (string[] args)
{
Tabela tabela = new Tabela (15); // 15 elementos
int n = 0, entrada, endereco;
117
Console.WriteLine ("Endereco: " + endereco);
}
}
} while (entrada != 0);
}
}
}
using System;
namespace Dados30
{
public class Tabela
{
private int max;
private bool[] situacao;
private int[] valor;
// ---------------------------------------------- Tabela
public Tabela (int numElementos)
{
max = numElementos;
situacao = new bool[max];
valor = new int[max];
for (int i = 0; i < situacao.Length; i++) {
situacao [i] = false;
valor [i] = 0;
}
}
// ---------------------------------------------- consultaLimite
public int consultaLimite ()
{
return(max);
}
// ---------------------------------------------- testaTabela
public bool testaTabela ()
{
for (int i = 0; i < situacao.Length; i++) {
if (situacao [i] == false) {
return(false);
}
}
return(true);
}
// ---------------------------------------------- insereTabela
public void insereTabela (int entrada)
{
int endereco, n = -1;
bool lotado = testaTabela ();
if (!lotado) {
endereco = entrada % max;
while (situacao [endereco] == true) {
endereco++;
n++;
}
if (n < max) {
valor [endereco] = entrada;
situacao [endereco] = true;
}
} else {
Console.WriteLine ("Status: TABELA CHEIA ...");
}
}
// ---------------------------------------------- hashing
public int hashing (int entrada)
118
{
int endereco;
Resultado do Programa:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Número [0 para Sair]: 383
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
0 0 0 0 0 0 0 0 383 0 0 0 0 0 0
Número [0 para Sair]: 487
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
0 0 0 0 0 0 0 487 383 0 0 0 0 0 0
Número [0 para Sair]: 235
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
0 0 0 0 0 0 0 487 383 0 235 0 0 0 0
Número [0 para Sair]: 527
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
0 0 527 0 0 0 0 487 383 0 235 0 0 0 0
Número [0 para Sair]: 510
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
510 0 527 0 0 0 0 487 383 0 235 0 0 0 0
Número [0 para Sair]: 320
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
510 0 527 0 0 320 0 487 383 0 235 0 0 0 0
Número [0 para Sair]: 203
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
510 0 527 0 0 320 0 487 383 203 235 0 0 0 0
Número [0 para Sair]: 108
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
510 0 527 108 0 320 0 487 383 203 235 0 0 0 0
Número [0 para Sair]: 563
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
510 0 527 108 0 320 0 487 383 203 235 563 0 0 0
Número [0 para Sair]: 500
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
510 0 527 108 0 320 500 487 383 203 235 563 0 0 0
Número [0 para Sair]: 646
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
510 646 527 108 0 320 500 487 383 203 235 563 0 0 0
119
Número [0 para Sair]: 103
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
510 646 527 108 0 320 500 487 383 203 235 563 0 103 0
Número [0 para Sair]: 0
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
510 646 527 108 0 320 500 487 383 203 235 563 0 103 0
Valor a ser CONSULTADO: 563
Endereco: 11
Valor a ser CONSULTADO:
120
5. Classificação de Dados (Ordenação)
using System;
namespace Dados31
{
class MainClass
{
public static void Main (string[] args)
{
const int QUANT = 10;
int[] v = new int[QUANT];
int n = -1;
do {
n++;
Console.Write ("Valor: ");
121
String s = Console.ReadLine ();
v [n] = Convert.ToInt32 (s);
} while (v [n] != 0 && n < QUANT);
if (v [n] == 0) {
n--;
}
sortForcaBruta (v, n);
exibeLista (v, n);
}
// ------------------------------------------------------- sortForcaBruta
static void sortForcaBruta (int[] v, int n)
{
for (int i = 0; i < n; i++) {
for (int j = i + 1; j <= n; j++) {
if (v [i] > v [j]) {
int temp = v [i];
v [i] = v [j];
v [j] = temp;
}
}
}
}
// ------------------------------------------------------- exibe
static void exibeLista (int[] v, int n)
{
Console.Write ("Lista: ");
if (n == -1) {
Console.Write ("Vazia");
} else {
for (int i = 0; i <= n; i++) {
Console.Write (v [i] + " ");
}
Console.WriteLine ();
}
}
}
}
Resultado do Programa:
Valor: 30
Valor: 50
Valor: 40
Valor: 20
Valor: 10
Valor: 0
Lista: 10 20 30 40 50
Exemplo:
122
Figura 25: Exemplo de Tabela de Nomes
using System;
namespace Dados32
{
class MainClass
{
public static void Main (string[] args)
{
const int QUANT = 10;
String[] v = new String[QUANT];
int[] vio = new int[QUANT];
int u = -1;
char tecla;
do {
u++;
Console.Write ("Nome: ");
v [u] = Console.ReadLine ();
Console.Write ("Continua [S/N] ?");
vio [u] = 0;
do {
String s = Console.ReadLine ();
s = s.ToLower ();
tecla = s [0];
} while (tecla != 's' && tecla != 'n');
} while (tecla != 'n' && u <= QUANT);
for (int i = 0; i <= u; i++) {
vio [i] = i;
}
for (int i = 0; i < u; i++) { // sort no vio
for (int j = i + 1; j <= u; j++) {
if (v [vio [i]].CompareTo (v [vio [j]]) > 0) {
int temp = vio [i];
vio [i] = vio [j];
vio [j] = temp;
}
}
}
123
Console.WriteLine ("Lista de Nomes Ordenados");
for (int i = 0; i <= u; i++) {
Console.WriteLine ("Nome: " + v [vio [i]]);
}
}
}
}
Resultado do Programa:
Nome: Carla
Continua [S/N] ?s
Nome: Beatriz
Continua [S/N] ?s
Nome: Ana
Continua [S/N] ?n
Lista de Nomes Ordenados
Nome: Ana
Nome: Beatriz
Nome: Carla
Exemplo:
package dados33;
124
public int prox = -1;
}
using System;
namespace Dados33
{
class MainClass
{
public static void Main (string[] args)
{
const int QUANT = 10;
Tabela[] t = new Tabela[QUANT];
Tabela[] ta = new Tabela[QUANT];
int j = 0, k, m, u = -1;
int anterior, primeiro;
char tecla;
do {
u++;
Console.Write ("Nome: ");
String s = Console.ReadLine ();
t [u] = new Tabela ();
t [u].nome = s;
t [u].prox = -1;
Console.Write ("Continua [S/N]? ");
do {
s = Console.ReadLine ().ToLower ();
tecla = s [0];
} while (tecla != 's' && tecla != 'n');
} while (tecla != 'n' && u < QUANT);
primeiro = 0;
for (int i = 1; i <= u; i++) {
if (t [i].nome.CompareTo (t [primeiro].nome) < 0) {
primeiro = i;
}
}
t [primeiro].prox = 0;
anterior = primeiro;
do {
m = copia (t, ta, u);
if (m != 0) {
if (m >= 1) {
int i = 1;
j = 0;
do {
if (ta [i].nome.CompareTo (ta [j].nome) < 0) {
j = i;
}
i++;
} while (i <= m);
}
} else {
j = 0;
}
k = verifica (t, ta, j);
t [anterior].prox = k;
t [k].prox = 0;
anterior = k;
} while (m != 0);
j = primeiro;
Console.WriteLine ("Lista de Nomes Ordenados por Encadeamento");
for (int i = 0; i <= u; i++) {
Console.WriteLine (t [j].nome);
125
j = t [j].prox;
}
}
// --------------------------------------------------- verifica
static int verifica (Tabela[] t, Tabela[] ta, int j)
{
bool sai;
int i = 0;
do {
sai = false;
if (t [i].nome.CompareTo (ta [j].nome) == 0) {
j = i;
sai = true;
}
i++;
} while (!sai);
return(j);
}
// ---------------------------------------------- Copia
static int copia (Tabela[] t, Tabela[] ta, int n)
{
int m = -1;
Resultado do Programa:
Nome: Beatriz
Continua [S/N]? s
Nome: Debora
Continua [S/N]? s
Nome: Ana
Continua [S/N]? s
Nome: Carla
Continua [S/N]? n
Lista de Nomes Ordenados por Encadeamento
Ana
Beatriz
Carla
Debora
·
Por Inserção
·
Por Troca
·
Por Seleção
126
Observação: Para os seguintes métodos considere que as
entradas são feitas no vetor v, logo após é criado o vetor c
(chaves) e o vetor e (endereços). A ordenação é feita no
vetor c e o vetor e é o vetor indireto de ordenação, ou seja,
será mantido o vetor de entrada intacto.
127
A classificação acontece por meio de interações, cada
elemento do segundo segmento é inserido ordenadamente no
primeiro até que o segundo segmento acabe. Por exemplo:
using System;
namespace Dados34
{
class MainClass
{
public static void Main (string[] args)
{
const int QUANT = 10;
int[] v = new int[QUANT];
int[] c = new int[QUANT];
int[] e = new int[QUANT];
int j, k, u = -1, temp;
int chave, endereco;
do {
u++;
Console.Write ("Número: ");
String s = Console.ReadLine ();
temp = Convert.ToInt32 (s);
if (temp != 0) {
v [u] = temp;
128
} else {
u--;
}
} while (temp != 0 && u < QUANT);
for (int i = 0; i <= u; i++) {
c [i] = v [i];
e [i] = i;
}
for (int i = 1; i <= u; i++) {
k = 0;
j = i - 1;
chave = c [i];
endereco = e [i];
while (j >= 0 && k == 0) {
if (chave < c [j]) {
c [j + 1] = c [j];
e [j + 1] = e [j];
j--;
} else {
k = j + 1;
}
}
c [k] = chave;
e [k] = endereco;
}
Console.Write (" Valores: ");
for (int i = 0; i <= u; i++) {
Console.Write (c [i] + " ");
}
Console.WriteLine ();
Resultado do Programa:
Número: 20
Número: 40
Número: 50
Número: 30
Número: 10
Número: 0
Valores: 10 20 30 40 50
Endereços: 4 0 3 1 2
129
Figura 30: Método da Bolha (Bubble Sort)
using System;
namespace Dados35
{
class MainClass
{
public static void Main (string[] args)
{
const int QUANT = 10;
int[] v = new int[QUANT];
int[] c = new int[QUANT];
int[] e = new int[QUANT];
int j = 0, n = -1, m, temp;
int chave, endereco;
bool troca;
do {
n++;
Console.Write ("Número: ");
String s = Console.ReadLine ();
temp = Convert.ToInt32 (s);
if (temp != 0) {
v [n] = temp;
} else {
n--;
130
}
} while (temp != 0 && n < QUANT);
for (int i = 0; i <= n; i++) {
c [i] = v [i];
e [i] = i;
}
m = n - 1;
do {
troca = true;
for (int i = 0; i <= m; i++) {
if (c [i] > c [i + 1]) {
chave = c [i];
c [i] = c [i + 1];
c [i + 1] = chave;
endereco = e [i];
e [i] = e [i + 1];
e [i + 1] = endereco;
j = i;
troca = false;
}
}
m = j;
} while (!troca);
Console.Write ("Lista Ordenada: ");
for (int i = 0; i <= n; i++) {
Console.Write (c [i] + " ");
}
Console.WriteLine ();
}
}
}
Resultado do Programa:
Número: 20
Número: 40
Número: 50
Número: 30
Número: 10
Número: 0
Lista Ordenada: 10 20 30 40 50
131
Figura 31: Método por Seleção Direta
using System;
namespace Dados36
{
class MainClass
{
public static void Main (string[] args)
{
const int QUANT = 10;
int[] v = new int[QUANT];
int[] c = new int [QUANT];
int[] e = new int [QUANT];
int j, n = -1, min, temp;
int chave, endereco;
do {
n++;
Console.Write ("Número: ");
string s = Console.ReadLine ();
temp = Convert.ToInt32 (s);
if (temp != 0) {
v [n] = temp;
} else {
n--;
}
} while (temp != 0 && n < QUANT);
for (int i = 0; i <= n; i++) {
c [i] = v [i];
e [i] = i;
}
for (int i = 0; i <= n - 1; i++) {
min = i;
for (j = i + 1; j <= n; j++) {
132
if (c [j] < c [min]) {
min = j;
}
}
chave = c [i];
c [i] = c [min];
c [min] = chave;
endereco = e [i];
e [i] = e [min];
e [min] = endereco;
}
Console.Write ("Lista Ordenada: ");
for (int i = 0; i <= n; i++) {
Console.Write (c [i] + " ");
}
Console.WriteLine ();
}
}
}
Resultado do Programa:
Número: 20
Número: 40
Número: 50
Número: 30
Número: 10
Número: 0
Lista Ordenada: 10 20 30 40 50
133
6. Árvores
Definição
Terminologia
Grau
134
Observação: Se um nodo não possuir nenhuma sub-árvore é
chamado de nó terminal ou folha.
Nível
Exemplo:
Altura
135
Floresta
α) Representação Hierárquica
136
χ) Representação por Expressão Parentetizada (Parênteses
Aninhados)
( A ( B ( ) C ( D ( G ( ) H ( ) ) E ( ) F ( I ( ) ) ) ) )
Figura 39: Representação por Expressão Parentetizada de uma Árvore
A 2 B 0 C 3 D 2 G 0 H 0 E 0 F 1 I 0
Figura 40: Representação por Expressão não Parentetizada de uma Árvore
137
esquerda (Te) da raiz só existam nós com chaves menores que a
chave da raiz. E a sub-árvore à direita (Td) só pode conter
nós com valores maiores que a raiz. Com esta reestruturação
da árvore, a busca de um determinado nó torna-se trivial. O
acesso aos dados pode ser feito então através de funções
recursivas.
Propriedades
Expressão: (3 + 6) * (4 – 1) + 5
Figura 43: Expressão representação por uma Árvore Binária
138
Conversão de Árvore Genérica em Árvore Binária
139
6.3 Representações
Exemplo:
140
Observações (considere a árvore da página anterior):
Vantagens
Desvantagens
141
public class Tree {
public Tree esq;
public char info;
public Tree dir;
}
Exemplo:
Caminhamento: ABDECFG
Figura 47: Caminhamento Pré-Fixado (Pré-Ordem)
142
Caminhamento: DBEACGF
Figura 48: Caminhamento In-Fixado (Central)
Caminhamento: DEBGFCA
Figura 49: Caminhamento Pós-Fixado
143
Como vantagens das funções recursivas tem-se:
144
Console.Write (a.info + “ “); // mostra raiz
}
}
using System;
namespace Dados37
{
public class Tree
{
public Tree esq;
public char info;
public Tree dir;
// --------------------------------------------- criaTree
public Tree (Tree esquerda, char informacao, Tree direita)
{
esq = esquerda;
info = informacao;
dir = direita;
}
}
}
using System;
namespace Dados37
{
class MainClass
{
public static void Main (string[] args)
{
Tree a1 = new Tree (null, 'd', null);
Tree a2 = new Tree (null, 'e', null);
Tree a3 = new Tree (a1, 'b', a2);
Tree a4 = new Tree (null, 'g', null);
Tree a5 = new Tree (a4, 'f', null);
Tree a6 = new Tree (null, 'c', a5);
Tree a = new Tree (a3, 'a', a6);
145
return(true);
} else {
return(false);
}
}
// --------------------------------------------- caminhamentoPreOrdem
static void caminhamentoPreOrdem (Tree a)
{
if (!treeVazia (a)) {
Console.Write (a.info + " "); // mostra raiz
caminhamentoPreOrdem (a.esq); // mostra sub_esq
caminhamentoPreOrdem (a.dir); // mostra sub_dir
}
}
// --------------------------------------------- caminhamentoInFixado
static void caminhamentoInFixado (Tree a)
{
if (!treeVazia (a)) {
caminhamentoInFixado (a.esq); // mostra sub_esq
Console.Write (a.info + " "); // mostra raiz
caminhamentoInFixado (a.dir); // mostra sub_dir
}
}
// --------------------------------------------- caminhamentoPosFixado
static void caminhamentoPosFixado (Tree a)
{
if (!treeVazia (a)) {
caminhamentoPosFixado (a.esq); // mostra sub_esq
caminhamentoPosFixado (a.dir); // mostra sub_dir
Console.Write (a.info + " "); // mostra raiz
}
}
}
}
Resultado do Programa:
Caminhamentos na Árvore
Pré-Ordem: a b d e c f g
In-Fixado: d b e a c g f
Pós-Fixado: d e b g f c a
146
ordem in-Fixado (esquerda -> raiz -> direita, ou seja,
caminhamento ERD). Onde a chave de cada nó da árvore deve
ser:
·
maior ou igual que qualquer chave na sua sub-árvore esquerda;
using System;
namespace Dados38
{
public class Tree
{
public Tree esq;
public char info;
public Tree dir;
// --------------------------------------------- criaTree (construtor)
public Tree (Tree esquerda, char informacao, Tree direita)
{
esq = esquerda;
info = informacao;
dir = direita;
}
}
}
using System;
namespace Dados38
{
class MainClass
{
public static void Main (string[] args)
{
Tree a1 = new Tree (null, 'd', null);
Tree a2 = new Tree (null, 'e', null);
Tree a3 = new Tree (a1, 'b', a2);
Tree a4 = new Tree (null, 'g', null);
Tree a5 = new Tree (a4, 'f', null);
Tree a6 = new Tree (null, 'c', a5);
Tree a = new Tree (a3, 'a', a6);
Tree tree = new Tree (null, 'x', null);
147
char info;
if (raiz == null) {
return(null);
} else {
if (raiz.info == chave) { // busca na raiz
return(raiz);
148
} else {
a1 = buscaTree (raiz.esq, chave); // busca na sub-árvore esquerda
if (a1 == null) {
a1 = buscaTree (raiz.dir, chave); // busca na sub-árvore direita
}
}
return(a1);
}
}
}
}
Resultado do Programa:
In-Fixado:
d b e a c g f
Info [x - abandona]: b
Status: Ok, Nodo Valido
Info [x - abandona]: y
Status: Nodo Invalido
Info [x - abandona]: x
Balanceamento em Árvores
149
O balanceamento de uma árvore binária pode ser: estático
ou dinânico (AVL). O balanceamento estático de uma árvore
binária consiste em construir uma nova versão da árvore,
reorganizando-a, enquanto que no balanceamento dinâmico (AVL)
a cada nova operação realizada na árvore binária, ela sobre
rotações deixando-a balanceada.
150
a) Inserção dos nós: 10, 20 e 30
151
Para cada caso acima, aplica-se um tipo de rotação a
árvore:
152
d) Rotação dupla à direita
Dicas:
using System;
namespace Dados39
{
public class AvlNode
{
public AvlNode esq;
public int info;
public AvlNode dir;
public int altura;
// ----------------------------------------- Construtor
public AvlNode (int info)
{
this.esq = null;
this.info = info;
153
this.dir = null;
}
// ----------------------------------------- Construtor
public AvlNode (AvlNode esquerda, int info, AvlNode direita)
{
this.esq = esquerda;
this.info = info;
this.dir = direita;
this.altura = 0;
}
}
}
using System;
namespace Dados39
{
public class AvlTree
{
private static int maxAVL (int a, int b)
{
if (a > b) {
return(a);
} else {
return(b);
}
}
// -------------------------------------------- alturaAVL
private static int alturaAVL (AvlNode t)
{
if (t == null) {
return(-1);
} else {
return(t.altura);
}
}
// -------------------------------------------- rotacaoEsquerdaAVL
private static AvlNode rotacaoEsquerdaAVL (AvlNode nodoOut)
{
AvlNode nodoIn = nodoOut.esq;
int a, b;
nodoOut.esq = nodoIn.dir;
nodoIn.dir = nodoOut;
a = AvlTree.alturaAVL (nodoOut.esq);
b = AvlTree.alturaAVL (nodoOut.dir);
nodoOut.altura = AvlTree.maxAVL (a, b) + 1;
a = AvlTree.alturaAVL (nodoIn.esq);
b = nodoOut.altura;
nodoIn.altura = AvlTree.maxAVL (a, b) + 1;
return(nodoIn);
}
// -------------------------------------------- rotacalDireitaAVL
private static AvlNode rotacaoDireitaAVL (AvlNode nodoOut)
{
AvlNode nodoIn = nodoOut.dir;
int a, b;
nodoOut.dir = nodoIn.esq;
nodoIn.esq = nodoOut;
a = AvlTree.alturaAVL (nodoOut.esq);
b = AvlTree.alturaAVL (nodoOut.dir);
nodoOut.altura = AvlTree.maxAVL (a, b) + 1;
a = AvlTree.alturaAVL (nodoIn.dir);
b = nodoOut.altura;
154
nodoIn.altura = AvlTree.maxAVL (a, b) + 1;
return(nodoIn);
}
// -------------------------------------------- rotacaoDuplaEsquerdaAVL
private static AvlNode rotacaoDuplaEsquerdaAVL (AvlNode nodo)
{
nodo.esq = AvlTree.rotacaoDireitaAVL (nodo.esq);
return(AvlTree.rotacaoEsquerdaAVL (nodo));
}
// -------------------------------------------- rotacaoDuplaDireitaAVL
private static AvlNode rotacaoDuplaDireitaAVL (AvlNode nodo)
{
nodo.dir = AvlTree.rotacaoEsquerdaAVL (nodo.dir);
return(AvlTree.rotacaoDireitaAVL (nodo));
}
if (avl == null) {
avl = new AvlNode (null, x, null);
} else {
if (x > avl.info) {
avl.dir = insertAVL (x, avl.dir);
a = AvlTree.alturaAVL (avl.dir);
b = AvlTree.alturaAVL (avl.esq);
if (a - b == 2) {
if (x > avl.dir.info) {
avl = AvlTree.rotacaoDireitaAVL (avl);
} else {
avl = AvlTree.rotacaoDuplaDireitaAVL (avl);
}
}
} else {
if (x < avl.info) {
avl.esq = insertAVL (x, avl.esq);
a = AvlTree.alturaAVL (avl.esq);
b = AvlTree.alturaAVL (avl.dir);
if (a - b == 2) {
if (x < avl.esq.info) {
avl = AvlTree.rotacaoEsquerdaAVL (avl);
} else {
avl = AvlTree.rotacaoDuplaEsquerdaAVL (avl);
}
}
}
}
}
a = AvlTree.alturaAVL (avl.esq);
b = AvlTree.alturaAVL (avl.dir);
avl.altura = AvlTree.maxAVL (a, b) + 1;
return(avl);
}
// -------------------------------------------- vaziaAVL
155
public bool vaziaAVL ()
{
return this.raiz == null;
}
// -------------------------------------------- exibeAVL
public void exibeAVL ()
{
if (vaziaAVL ()) {
Console.WriteLine ("Status: AVL Vazia");
} else {
exibeAVL (this.raiz, 1);
}
}
// -------------------------------------------- exibeAVL (SobreCarga)
private void exibeAVL (AvlNode avl, int t)
{
if (avl != null) {
exibeAVL (avl.dir, t + 1);
for (int i = 0; i < t; i++) {
Console.Write (" ");
}
Console.WriteLine (avl.info + " ");
exibeAVL (avl.esq, t + 1);
}
}
}
}
using System;
namespace Dados39
{
class MainClass
{
public static void Main (string[] args)
{
AvlTree avl = new AvlTree ();
int info;
do {
Console.Write ("Info: ");
string s = Console.ReadLine ();
info = Convert.ToInt32 (s);
if (info != 0) {
avl.insertAVL (info);
}
} while (info != 0);
avl.exibeAVL ();
}
}
}
Resultado do Programa:
Info: 20
Info: 30
Info: 10
Info: 40
Info: 50
Info: 0
50
40
30
20
10
156
Programa online que demonstra inserções e remoções em uma árvore AVL:
http://www.site.uottawa.ca/~stan/csi2514/applets/avl/BT.html
a) Remoção do nó: 10
b) Remoção do nó: 40
157
Resultado: Com a remoção do nodo 40 a árvore ficará
desbalanceada, pois o nodo raiz ficará com Fb = -2. A solução
será fazer uma rotação simples à direita.
c) Remoção do nó: 10
d) Remoção do nó: 40
158
Resultado: Com a remoção do nodo 40 a árvore ficará
desbalanceada, pois o nodo raiz ficará com Fb = 2. A solução
será fazer uma rotação dupla à direita (rotação simples à
esquerda + rotação simples à direita).
159
7. Grafos
7.1 Conceitos
160
G(4,7) – 4 vértices e 7 arestas
Figura 53: Grafo com 4 vértices e 7 arestas
161
Figura 55: Vértice Isolado
Passeio é uma seqüência <v0, a1, v1, a2, ..., vk-1, ak,
vk> onde v0, v1,....,vk são vértices, a1, a2,...., ak são
arcos e, para cada (i, ai) é um arco de vi-1 a vi. O vértice
v0 é o início do passeio e o vértice vk é o seu término.
Um caminho é um passeio sem vértices repetidos. A
dimensão de um caminho ou trajeto é chamado de comprimento.
162
Diz-se que o grafo é conexo se para cada par de vértices
existe pelo menos um passeio que os une.
163
Grafo dirigido ou dígrafo
164
Tipos de Grafos
165
d) Ciclo: Um grafo ciclo de n vértices, denominado Cn, onde n
é maior ou igual a 3, é um grafo simples com n vértices v1,
v2, . . . , vn, e arestas v1v2, v2v3, . . ., vn−1vn, vnv1.
166
g) Planar: É um grafo onde não há cruzamento de arestas.
167
Lista de Adjacências para um grafo dirigido:
168
Matriz de Adjacências para um grafo dirigido:
169
d) Após visitar os vértices adjacentes, o primeiro da fila
torna-se o novo vértice inicial. Reinicia-se o processo.
e) O caminhamento termina quanto todos os vértices tiverem
sido visitados ou o vértice procurado for encontrado.
170
algoritmo de Dijkstra para encontrar a distância mínima
entre um vértice inicial (s) e um vértice final (v). Ele
determina a distância mínima entre s e os outros
vértices na ordem dessas distâncias mínimas, ou seja, os
vértices que se encontram mais próximos de s em primeiro
lugar.
Descrição do Algoritmo
171
Se o vértice vn coincidir com o vértice final então dist(Vn)
é a menor distância entre s e Vn , e parar a execução. Se não
coincidir, voltam-se a repetir os passos 1 , 2 e 3.
Se não for possível aplicar aqueles passos, ou porque
V(S) igual ao conjunto vazio ou qualquer que seja Vm não
pertencente a S então (V, Vm) não pertence ao conjunto V,
então não é possível determinar a distância mínima de s ao
vértice final.
using System;
namespace Dados40
{
public class Grafo
{
172
const int maxVertices = 6;
const int limite = 32767;
int[, ] valor = new int[maxVertices, maxVertices];
char[, ] adj = new char[maxVertices, maxVertices];
String[] rotulos = { "Spa", "Rio", "Vit", "Rec", "Sal", "Nat" };
// ------------------------------------ inicializaGrafo
public void inicializaGrafo ()
{
for (int l = 0; l < maxVertices; l++) {
for (int c = 0; c < maxVertices; c++) {
valor [l, c] = limite;
adj [l, c] = 'N';
}
}
}
// ------------------------------------ criaAresta
public void criaAresta (int origem, int destino, int info)
{
adj [origem, destino] = 'S';
valor [origem, destino] = info;
adj [destino, origem] = 'S';
valor [destino, origem] = info;
}
// ------------------------------------ imprimeGrafo
public void imprimeGrafo ()
{
for (int l = 0; l < maxVertices; l++) {
Console.Write (" " + l);
}
newline ();
for (int l = 0; l < maxVertices; l++) {
Console.Write (" " + rotulos [l]);
}
newline ();
}
// ------------------------------------ imprimeMatriz
public void imprimeMatriz ()
{
Console.WriteLine ("Matriz de Adjacencias");
for (int l = 0; l < maxVertices; l++) {
for (int c = 0; c < maxVertices; c++) {
Console.Write (valor [l, c] + " ");
}
newline ();
}
newline ();
}
// ---------------------------------------------- dijkstra
public void dijkstra (int origem, int destino, int[] precede)
{
int k, result;
int aux1, aux2;
int[] distancia = new int[maxVertices];
bool[] menorCaminho = new bool[maxVertices];
int atual, dc, menordist, novadist;
char parar = 'N';
173
menordist = limite;
dc = distancia [atual];
for (int i = 0; i < maxVertices; i++) {
if (menorCaminho [i] == false) {
if (adj [atual, i] == 'S') {
novadist = dc + valor [atual, i];
} else {
novadist = valor [atual, i];
}
if (novadist < distancia [i]) {
distancia [i] = novadist;
precede [i] = atual;
}
if (distancia [i] < menordist) {
menordist = distancia [i];
k = i;
}
}
}
if (atual == k) {
parar = 'S';
} else {
atual = k;
menorCaminho [atual] = false;
}
}
result = distancia [destino];
if (result == limite || result == 0) {
Console.Write ("\nNão há trajeto entre ", rotulos [origem] + " e " + rotulos [destino]);
} else {
Console.Write ("\nMenor caminho entre " + rotulos [origem] + " e " + rotulos [destino] + " = " + result);
Console.Write ("\nCaminho INVERSO Percorrido: ");
aux1 = precede [destino];
aux2 = destino;
while (aux1 != origem) {
Console.Write ("\n" + rotulos [aux1] + " -> " + rotulos [aux2] + "(" + valor [aux1, aux2] + ")");
aux2 = aux1;
aux1 = precede [aux1];
Console.Write ("\n" + rotulos [aux1] + " -> " + rotulos [aux2] + "(" + valor [aux1, aux2] + ")");
}
}
}
// ------------------------------------ imprimeCidades
public void imprimeCidades ()
{
String[] cidades = {"[0] - (Spa) - Sao Paulo",
"[1] - (Rio) - Rio de janeiro",
"[2] - (Vit) - Vitoria",
"[3] - (Rec) - Recife",
"[4] - (Sal) - Salvador",
"[5] - (Nat) - Natal"
};
for (int i = 0; i < maxVertices; i++) {
Console.WriteLine (cidades [i]);
}
newline ();
}
// ------------------------------------ newline
public void newline ()
{
Console.WriteLine ();
}
}
}
174
// ------------------------------------------------------ Fonte: Dados40.cs
using System;
namespace Dados40
{
class MainClass
{
public static void Main (string[] args)
{
const int maxVertices = 6;
const int limite = 32767;
Grafo grafo = new Grafo ();
int[] precede = new int [maxVertices];
char tecla;
int origem, destino;
String s;
grafo.inicializaGrafo ();
grafo.criaAresta (0, 1, 300);
grafo.criaAresta (0, 3, 400);
grafo.criaAresta (0, 4, 100);
grafo.criaAresta (1, 2, 100);
grafo.criaAresta (1, 5, 70);
grafo.criaAresta (2, 3, 50);
grafo.criaAresta (4, 5, 50);
grafo.criaAresta (3, 5, 150);
do {
grafo.imprimeMatriz ();
grafo.imprimeCidades ();
grafo.imprimeGrafo ();
int tam = maxVertices - 1;
Console.Write ("\n Origem [0..%d]: ", tam);
do {
s = Console.ReadLine ();
origem = Convert.ToInt32 (s);
} while (origem < 0 || origem > tam);
Console.Write ("Destino [0..%d]: ", tam);
do {
s = Console.ReadLine ();
destino = Convert.ToInt32 (s);
} while (destino < 0 || destino > tam);
grafo.dijkstra (origem, destino, precede);
Console.WriteLine ();
Console.Write ("\nRepetir [S/N]? ");
do {
s = Console.ReadLine ();
tecla = s [0];
} while (!strChr ("SsNn", tecla));
} while (strChr ("Ss", tecla));
}
// ----------------------------------------------------- strChr
static bool strChr (String s, char ch)
{
175
Resultado do Programa:
Matriz de Adjacencias
32767 300 32767 400 100 32767
300 32767 100 32767 32767 70
32767 100 32767 50 32767 32767
400 32767 50 32767 32767 150
100 32767 32767 32767 32767 50
32767 70 32767 150 50 32767
0 1 2 3 4 5
Spa Rio Vit Rec Sal Nat
Origem [0..%d]: 0
Destino [0..%d]: 5
Repetir [S/N]? n
176
8. Programas exemplos
Regras do Jogo:
using System;
using System.Collections.Generic;
namespace Torre
{
class MainClass
{
public static void Main (string[] args)
{
String s;
int In, Out;
177
Stack <int> p1 = new Stack<int> ();
Stack <int> p2 = new Stack<int> ();
Stack <int> p3 = new Stack<int> ();
bool ganhou = false, moveu = false;
p1.Push (3);
p1.Push (2);
p1.Push (1);
//p2.Push (0);
//p2.Push (0);
//p2.Push (0);
//p3.Push (0);
//p3.Push (0);
//p3.Push (0);
a = p1.Contains (1);
178
b = p1.Contains (2);
c = p1.Contains (3);
if (a && b && c) {
return(true);
} else {
return(false);
}
}
// -------------------------------------------- testaMaior
static bool testaMaior (Stack <int> p1, Stack <int> p2, Stack <int>p3, int In, int Out)
{
Object nodo;
int a = 0, b = 0;
switch (In) {
case 1:
nodo = p1.Peek ();
a = nodo.GetHashCode ();
break;
case 2:
nodo = p2.Peek ();
a = nodo.GetHashCode ();
break;
case 3:
nodo = p3.Peek ();
a = nodo.GetHashCode ();
break;
}
switch (Out) {
case 1:
if (p1.Count == 0) {
return(true);
} else {
nodo = p1.Peek ();
b = nodo.GetHashCode ();
}
break;
case 2:
if (p2.Count == 0) {
return(true);
} else {
nodo = p2.Peek ();
b = nodo.GetHashCode ();
}
break;
case 3:
if (p3.Count == 0) {
return(true);
} else {
nodo = p3.Peek ();
b = nodo.GetHashCode ();
}
break;
}
if (a < b)
return(true);
else {
if (a != 0 && b != 0) {
return(false);
}
}
return(true);
}
// -------------------------------------------- testaMovimento
static bool testaMovimento (Stack <int> p1, Stack <int> p2, Stack <int> p3, int In)
{
bool pode = false;
179
switch (In) {
case 1:
if (p1.Count == 0) {
Console.WriteLine ("Status: Impossivel mover (p1)");
} else {
pode = true;
}
break;
case 2:
if (p2.Count == 0) {
Console.WriteLine ("Status: Impossivel mover (p2)");
} else {
pode = true;
}
break;
case 3:
if (p3.Count == 0) {
Console.WriteLine ("Status: Impossivel mover (p3)");
} else {
pode = true;
}
break;
}
return(pode);
}
// -------------------------------------------- movePilha
static bool movePilha (Stack <int> p1, Stack <int> p2, Stack <int> p3, int a, int b)
{
Object nodo;
int In = 0;
bool moveu = false;
switch (a) {
case 1:
if (p1.Count != 0) {
nodo = p1.Pop ();
In = nodo.GetHashCode ();
} else {
In = 0;
}
break;
case 2:
if (p2.Count != 0) {
nodo = p2.Pop ();
In = nodo.GetHashCode ();
} else {
In = 0;
}
break;
case 3:
if (p3.Count != 0) {
nodo = p3.Pop ();
In = nodo.GetHashCode ();
} else {
In = 0;
}
break;
}
if (In != 0) {
switch (b) {
case 1:
p1.Push (In);
moveu = true;
break;
case 2:
p2.Push (In);
180
moveu = true;
break;
case 3:
p3.Push (In);
moveu = true;
break;
}
}
return(moveu);
}
// -------------------------------------------- exibePilhas
static void exibePilhas (Stack <int> p1, Stack <int> p2, Stack <int> p3)
{
int[] x = p1.ToArray ();
Console.Write ("Pilha 1: ");
for (int i = 0; i < p1.Count; i++) {
Console.Write (x [i] + " ");
}
Console.WriteLine ();
int[] y = p2.ToArray ();
Console.Write ("Pilha 2: ");
for (int i = 0; i < p2.Count; i++) {
Console.Write (y [i] + " ");
}
Console.WriteLine ();
int[] z = p3.ToArray ();
Console.Write ("Pilha 3: ");
for (int i = 0; i < p3.Count; i++) {
Console.Write (z [i] + " ");
}
Console.WriteLine ();
}
}
}
Resultado do Programa:
Pilha 1: 1 2 3
Pilha 2:
Pilha 3:
Move: 1
Para: 3
Pilha 1: 2 3
Pilha 2:
Pilha 3: 1
Move: 1
Para: 2
Pilha 1: 3
Pilha 2: 2
Pilha 3: 1
Move: 3
Para: 2
Pilha 1: 3
Pilha 2: 1 2
Pilha 3:
Move: 1
Para: 3
Pilha 1:
Pilha 2: 1 2
Pilha 3: 3
Move: 2
Para: 1
Pilha 1: 1
Pilha 2: 2
Pilha 3: 3
Move: 2
Para: 3
Pilha 1: 1
181
Pilha 2:
Pilha 3: 2 3
Move: 1
Para: 3
Pilha 1:
Pilha 2:
Pilha 3: 1 2 3
Status: VENCEDOR (p3)
Exemplo: (3 * (4 + 5))
Dicas:
Valores Válidos:
182
// -------------------------------------------------------- Fonte: Dados25.cs
using System;
namespace Dados25
{
public class PilhaInt
{
private const int m = 50;
private const int SUCESSO = 0;
private const int PILHA_CHEIA = 1;
private const int PILHA_VAZIA = 2;
private int topo;
private int[] elem = new int[m];
// ---------------------------------------------- criaPilha
public void criaPilha ()
{
topo = -1;
}
// ---------------------------------------------- push
public int push (int dado)
{
if (topo == m - 1) {
return(PILHA_CHEIA);
} else {
topo++;
elem [topo] = dado;
return(SUCESSO);
}
}
// ---------------------------------------------- pop
public int pop ()
{
if (topo != -1) {
topo--;
return(elem [topo + 1]);
}
return(0);
}
// ---------------------------------------------- exibePilha
public void exibePilha ()
{
if (topo != -1) {
Console.Write ("PilhaInt: ");
183
for (int i = topo; i >= 0; i--) {
Console.Write (elem [i] + " ");
}
Console.WriteLine ();
}
}
}
}
using System;
namespace Dados25
{
public class PilhaChar
{
private const int m = 50;
private const int SUCESSO = 0;
private const int PILHA_CHEIA = 1;
private const int PILHA_VAZIA = 2;
private int topo;
private char[] elem = new char[m];
// ---------------------------------------------- criaPilha
public void criaPilha ()
{
topo = -1;
}
// ---------------------------------------------- push
public int push (char dado)
{
if (topo == m - 1) {
return(PILHA_CHEIA);
} else {
topo++;
elem [topo] = dado;
return(SUCESSO);
}
}
// ---------------------------------------------- pop
public char pop ()
{
if (topo != -1) {
topo--;
return(elem [topo + 1]);
}
return('0');
}
// ---------------------------------------------- exibePilha
public void exibePilha ()
{
if (topo != -1) {
Console.Write ("PilhaChar: ");
for (int i = topo; i >= 0; i--) {
Console.Write (elem [i] + " ");
}
Console.WriteLine ();
}
}
}
}
using System;
namespace Dados25
184
{
class MainClass
{
public static void Main (string[] args)
{
PilhaInt p1 = new PilhaInt ();
PilhaChar p2 = new PilhaChar ();
const int m = 50;
String str;
int tipo, erro = 0;
int[] valor = { 0 };
char[] operador = { '0' };
int v1, v2, resposta;
185
}
if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
codifica = 2;
op [0] = ch;
}
if (ch == ')') {
codifica = 3;
}
return(codifica);
}
// -------------------------------------------- testaExpressao
static bool testaExpressao (String s)
{
int abre = 0, fecha = 0;
int n = s.Length;
for (int i = 0; i < n; i++) {
if (s [i] == '(') {
abre++;
} else {
if (s [i] == ')') {
fecha++;
}
}
}
if (abre == fecha) {
return(true);
}
return(false);
}
// ------------------------------------------ Calcula
static int calcula (int v1, int v2, char op)
{
switch (op) {
case '+':
return(v1 + v2);
case '-':
return(v1 - v2);
case '*':
return(v1 * v2);
case '/':
return(v1 / v2);
}
return(0);
}
}
}
Resultado do Programa:
Analisador de Expressões
Expressão: (3+(4*5))
PilhaInt: 3
PilhaChar: +
PilhaInt: 4 3
PilhaChar: * +
PilhaInt: 5 4 3
Resposta: 23
186
Exemplo de entrada de dados:
using System;
using System.Collections.Generic;
namespace AnalisadorExpressao
{
class MainClass
{
public static void Main (string[] args)
{
Stack <double> numeros = new Stack<double> ();
Stack <char> operadores = new Stack<char> ();
String s;
double resp = 0;
187
Object nodo = numeros.Pop ();
String st = nodo.ToString ();
double y = Convert.ToDouble (st);
nodo = numeros.Pop ();
st = nodo.ToString ();
double x = Convert.ToDouble (st);
nodo = operadores.Pop ();
String temp = nodo.ToString ();
char op = temp [0];
resp = calculaOperacao (x, y, op);
numeros.Push (resp);
exibePilhaDouble (numeros);
exibePilhaChar (operadores);
}
}
Console.WriteLine ("Resposta: " + resp);
} else {
Console.WriteLine ("Erro: Expressao Invalida");
}
}
// ---------------------------------------- calculaOperacao
static double calculaOperacao (double x, double y, char op)
{
double resp = 0;
switch (op) {
case '+':
resp = x + y;
break;
case '-':
resp = x - y;
break;
case '*':
resp = x * y;
break;
case '/':
if (y != 0) {
resp = x / y;
} else {
Console.WriteLine ("Erro Fatal: Divisão por Zero");
Environment.Exit (0);
}
break;
}
return(resp);
}
// ---------------------------------------- testaExpressao
static bool testaExpressao (String exp)
{
int abre = 0, fecha = 0;
188
double[] nodo = pilha.ToArray ();
Resultado do Programa:
Expressao: (4*(5+(4*3)/(3-1)))
Pilha: 4
Pilha:
Pilha: 5 4
Pilha: *
Pilha: 4 5 4
Pilha: + *
Pilha: 3 4 5 4
Pilha: * + *
Pilha: 12 5 4
Pilha: + *
Pilha: 3 12 5 4
Pilha: / + *
Pilha: 1 3 12 5 4
Pilha: - / + *
Pilha: 2 12 5 4
Pilha: / + *
Pilha: 6 5 4
Pilha: + *
Pilha: 11 4
Pilha: *
Pilha: 44
Pilha:
Resposta: 44
189
8.4 Calculadora Polonesa Reversa
using System;
namespace Polonesa
{
public class PolonesaReversa
{
private double x, y, resp = 0;
private char op;
private int erro;
// ............................................. métodos públicos da classe
public PolonesaReversa ()
{ // construtor
erro = 0;
}
190
Console.WriteLine ("by Polonesa Reversa");
Environment.Exit (0);
}
op = s [0];
} while (!strChr ("+-*/Pp", op));
operaCalculadora ();
exibeCalculadora ();
} while (!s.Equals (""));
}
// ---------------------------- operaCalculadora
private void operaCalculadora ()
{
switch (op) {
case '+':
resp = soma (x, y);
break;
case '-':
resp = subtracao (x, y);
break;
case '*':
resp = multiplicacao (x, y);
break;
case '/':
if (y == 0)
erro = 1; // divisão por zero
else
resp = divisao (x, y);
break;
case 'P':
case 'p':
resp = power (x, y); // potência
break;
}
}
// ---------------------------- exibeCalculadora
private void exibeCalculadora ()
{
if (erro == 1) {
Console.WriteLine ("Erro: Divisão por Zero");
} else {
if (erro == 2) {
Console.WriteLine ("Erro: Raiz Complexa");
} else {
if (erro == 3) {
Console.WriteLine ("Erro: Tangente Inválida");
} else {
Console.WriteLine (resp);
}
}
}
}
// ................................................ métodos privados da classe
// ---------------------------- strChr
private bool strChr (String s, char ch)
{
191
}
// ---------------------------- subtração
private double subtracao (double x, double y)
{
return(x - y);
}
// ---------------------------- multiplicação
private double multiplicacao (double x, double y)
{
return(x * y);
}
// ---------------------------- divisão
private double divisao (double x, double y)
{
if (y == 0) {
erro = 1;
return(-1);
}
return(x / y);
}
// ---------------------------- power
private double power (double x, double y)
{
return(Math.Pow (x, y));
}
}
}
using System;
namespace Tower
{
class MainClass
{
public static void Main (string[] args)
{
Pilha p1 = new Pilha (3);
Pilha p2 = new Pilha (3);
Pilha p3 = new Pilha (3);
String s;
int t1, t2;
int valor1 = 0, valor2;
bool erro = false;
p1.Push (30);
p1.Push (20);
p1.Push (10);
do {
p1.Exibe ("p1: ");
p2.Exibe ("p2: ");
p3.Exibe ("p3: ");
Console.Write ("De: ");
s = Console.ReadLine ();
t1 = Convert.ToInt32 (s);
if (t1 != 0) {
switch (t1) {
case 1:
valor1 = p1.Pop ();
192
break;
case 2:
valor1 = p2.Pop ();
break;
case 3:
valor1 = p3.Pop ();
break;
}
if (valor1 == -1) {
Console.WriteLine ("Status: Movimento Inválido");
} else {
erro = false;
Console.Write ("Para: ");
s = Console.ReadLine ();
t2 = Convert.ToInt32 (s);
switch (t2) {
case 1:
if (!p1.Empty ()) {
valor2 = p1.Consulta ();
if (valor1 > valor2) {
Console.WriteLine ("Status: Quebra da Regra");
erro = true;
} else {
p1.Push (valor1);
}
} else {
p1.Push (valor1);
}
break;
case 2:
if (!p2.Empty ()) {
valor2 = p2.Consulta ();
if (valor1 > valor2) {
Console.WriteLine ("Status: Quebra da Regra");
erro = true;
} else {
p2.Push (valor1);
}
} else {
p2.Push (valor1);
}
break;
case 3:
if (!p3.Empty ()) {
valor2 = p3.Consulta ();
if (valor1 > valor2) {
Console.WriteLine ("Status: Quebra da Regra");
erro = true;
} else {
p3.Push (valor1);
}
} else {
p3.Push (valor1);
}
break;
}
}
if (erro) {
switch (t1) {
case 1:
p1.Push (valor1);
break;
case 2:
p2.Push (valor1);
break;
case 3:
p3.Push (valor1);
193
break;
}
}
}
if (p2.Full () || p3.Full ()) {
Console.WriteLine ("Status: Winner");
Environment.Exit (0);
}
} while (t1 != 0);
}
}
}
using System;
namespace Tower
{
public class Pilha
{
int[] vet;
int topo;
int max;
// ------------------------------------ construtor
public Pilha (int numeroElementos)
{
vet = new int[numeroElementos];
topo = -1;
max = numeroElementos;
}
// ------------------------------------ Push
public void Push (int valor)
{
if (topo < max - 1) {
topo++;
vet [topo] = valor;
} else {
Console.WriteLine ("Status: Pilha Cheia");
Environment.Exit (0);
}
}
// ------------------------------------ Pop
public int Pop ()
{
int valor;
if (topo >= 0) {
valor = vet [topo];
topo--;
} else {
//System.out.println("Status: Pilha Vazia");
return(-1);
}
return(valor);
}
// ------------------------------------ Consulta
public int Consulta ()
{
int valor;
if (topo >= 0) {
valor = vet [topo];
} else {
//System.out.println("Status: Pilha Vazia");
return(-1);
}
194
return(valor);
}
// ------------------------------------ Empty
public bool Empty ()
{
if (topo == -1) {
return(true);
}
return(false);
}
// ------------------------------------ Full
public bool Full ()
{
if (topo == max - 1) {
return(true);
}
return(false);
}
// ------------------------------------ Exibe
public void Exibe (String s)
{
Console.Write (s + "[");
for (int i = 0; i < topo; i++) {
Console.Write (vet [i] + ",");
}
if (topo >= 0) {
Console.WriteLine (vet [topo] + "]");
} else {
Console.WriteLine ("]");
}
}
}
}
Resultado do Programa:
p1: [30,20,10]
p2: []
p3: []
De: 1
Para: 3
p1: [30,20]
p2: []
p3: [10]
De: 1
Para: 2
p1: [30]
p2: [20]
p3: [10]
De: 3
Para: 2
p1: [30]
p2: [20,10]
p3: []
De: 1
Para: 3
p1: []
p2: [20,10]
p3: [30]
De: 2
Para: 1
p1: [10]
p2: [20]
p3: [30]
De: 2
Para: 3
p1: [10]
p2: []
195
p3: [30,20]
De: 1
Para: 3
Status: Winner
196
8.6 Jogo Quebra-Cabeças
A seguir é visto a implementação de um jogo chamado
Quebra-Cabeças, cujo objetivo é colocar os números de 1 à 8
em ordem crescente, conforme exemplo abaixo:
using System;
namespace Cabeca
{
class MainClass
{
public static void Main (string[] args)
{
Tabuleiro tabuleiro = new Tabuleiro ();
tabuleiro.sorteiaNumeros ();
tabuleiro.exibeTabuleiro ();
tabuleiro.jogadasJogador ();
}
}
}
using System;
namespace Cabeca
{
public class Tabuleiro
{
private int[,] matriz = new int [3, 3];
private int[,] certa = {{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 0 }
};
private int jogadas = 0;
// --------------------------------- verificaVitoria
private bool verificaVitoria ()
{
for (int l = 0; l < 3; l++) {
for (int c = 0; c < 3; c++) {
if (matriz [l, c] != certa [l, c]) {
return(false);
}
}
}
return(true);
}
// --------------------------------- verificaDeslocamento
197
private void verificaDeslocamento (int num)
{
int lin = 0, col = 0;
int ll = 0, cc = 0;
do {
Console.Write ("Jogada (" + jogadas + "): ");
String s = Console.ReadLine ();
tecla = s [0];
if (strChr ("12345678", tecla)) {
verificaDeslocamento (tecla - 48);
jogadas++;
if (jogadas == 99) {
Console.WriteLine ("Game Over");
Environment.Exit (0);
}
}
} while (tecla != '0');
}
// --------------------------------- exibeTabuleiro
public void exibeTabuleiro ()
{
for (int l = 0; l < 3; l++) {
for (int c = 0; c < 3; c++) {
if (matriz [l, c] != 0) {
Console.Write (matriz [l, c] + " ");
} else {
Console.Write (" ");
}
}
Console.WriteLine ();
}
}
198
// --------------------------------- sorteiaNumeros
public void sorteiaNumeros ()
{
Random rnd = new Random ();
for (int i = 1; i <= 8; i++) {
bool ok = false;
do {
int l = (int)rnd.Next (3);
int c = (int)rnd.Next (3);
if (matriz [l, c] == 0) {
matriz [l, c] = i;
ok = true;
}
} while (!ok);
}
}
// --------------------------------- strChr
private bool strChr (String s, char tecla)
{
int n = s.Length;
Resultado do Programa:
6 1 7
2 3
4 5 8
Jogada (0): 6
1 7
6 2 3
4 5 8
Jogada (1): 1
1 7
6 2 3
4 5 8
Jogada (2): 7
1 7
6 2 3
4 5 8
Jogada (3): 0
199