Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ListaEncadeada {
- private No cabeca;
- private int tamanho;
- public ListaEncadeada(){
- this.tamanho = 0;
- this.cabeca = null;
- }
- public int getTamanho(){
- return this.tamanho;
- }
- public void mostrarLista(){
- if(this.tamanho == 0){
- System.out.println("Lista vazia.");
- }else{
- No ptr = this.cabeca;
- System.out.println("Tamanho da lista :"+this.tamanho);
- System.out.println("Elementos da lista:");
- for(int count = 0; count < this.tamanho; count++){
- System.out.println("\tValor : "+ptr.getValor());
- System.out.println("\tNo : "+(count+1));
- ptr = ptr.getProximo();
- System.out.println();
- }
- System.out.println();
- }
- }
- public void insereComecoLista(int valor){
- if(this.tamanho==0){
- No novoNo = new No();
- novoNo.setValor(valor);
- novoNo.setProximo(this.cabeca);
- this.cabeca = novoNo;
- this.tamanho = this.tamanho + 1;
- }else{
- No novoNo2 = new No();
- novoNo2.setValor(valor);
- novoNo2.setProximo(this.cabeca);
- this.cabeca = novoNo2;
- this.tamanho = this.tamanho + 1;
- }
- }
- public void insereFinalLista(int valor){
- No novoNo = new No();
- No aux = this.cabeca;
- while(aux.getProximo() != null){
- aux = aux.getProximo();
- }
- novoNo.setProximo(null);
- novoNo.setValor(valor);
- aux.setProximo(novoNo);
- this.tamanho = this.tamanho + 1;
- }
- public void insere(int valor, int posicao){
- No aux = this.cabeca;
- if(posicao==1){
- this.insereComecoLista(valor);
- }else if(posicao==this.tamanho + 1){
- this.insereFinalLista(valor);
- }else if(posicao > this.tamanho || posicao <=0){
- System.out.println("Entrada invalida.");
- }else{
- for(int i = 1; i < posicao - 1; i++){
- aux = aux.getProximo();
- }
- No novoNo = new No();
- novoNo.setValor(valor);
- novoNo.setProximo(aux.getProximo());
- aux.setProximo(novoNo);
- this.tamanho = this.tamanho + 1;
- }
- }
- public void removeInicioLista(){
- if(this.tamanho==0){
- System.out.println("A lista está vazia.");
- }else{
- No aux = this.cabeca;
- cabeca = cabeca.getProximo();
- aux = null;
- this.tamanho = this.tamanho - 1;
- }
- }
- public void removeMeioLista(int posicao){
- if(this.tamanho==0){
- System.out.println("A lista está vazia.");
- }else{
- No aux = this.cabeca;
- No anterior = this.cabeca;
- for(int count = 1; count <= posicao - 1; count++){
- anterior = aux;
- aux = aux.getProximo();
- }
- anterior.setProximo(aux.getProximo());
- this.tamanho = this.tamanho - 1;
- aux = null;
- }
- }
- public void removeLista(int posicao){
- if(posicao == 1){
- this.removeInicioLista();
- }else{
- this.removeMeioLista(posicao);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment