elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Introducción a la Factorización De Semiprimos (RSA)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Java
| | | |-+  invertir cola
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: invertir cola  (Leído 5,986 veces)
sheiking

Desconectado Desconectado

Mensajes: 10


Ver Perfil
invertir cola
« en: 13 Febrero 2019, 17:23 pm »

hola que tal cree una cola con los métodos básicos de agregar eliminar y mostrar los elementos de la cola pero me gustaría saber como podría invertir los datos de este

eh buscado en varios post acerca de como invertir una cola pero no eh podido solucionar mi problema me gustaría saber si me pueden ayudar

aquí les adjunto el código  
Código
  1. package clientqueue;
  2.  
  3.  
  4. public class Queue<E> {
  5.      public static final int CAPACITY  =100000;
  6.      private E[] data;
  7.      private int size=0;
  8.  
  9.      public Queue() {
  10.         this.data  = (E[])new Object[this.CAPACITY];
  11.      }
  12.  
  13.      public boolean isEmpty(){        
  14.         return (this.size==0);
  15.      }
  16.  
  17.      public int size(){
  18.  
  19.         return (this.size);
  20.    }
  21.  
  22.      public void push(E value){
  23.        this.data[this.size] = value;
  24.        this.size++;
  25.    }
  26.  
  27.      public E pop() throws Exception{
  28.        E result=null;
  29.        if (this.isEmpty()){
  30.            throw new Exception("La cola está vacía");
  31.    }
  32.        result = this.data[0];
  33.  
  34.      for (int i=0;i<this.size-1;i++){
  35.            data[i]=data[i+1];            
  36.        }
  37.        this.data[this.size]= null;
  38.        this.size--;        
  39.        return result;
  40.  
  41.      }
  42.      public E peek() throws Exception{
  43.  
  44.        E result=null;
  45.        if (this.isEmpty()){
  46.            throw new Exception("La Cola está vacía");
  47.        }
  48.        result = this.data[0];
  49.        return result;
  50.    }
  51.     public E peekLast() throws Exception{
  52.  
  53.        E result=null;
  54.        if (this.isEmpty()){
  55.            throw new Exception("La Cola está vacía");
  56.        }
  57.        result = this.data[size-1];
  58.        return result;
  59.    }
  60.  
  61.     @Override
  62.    public String toString()
  63.    {
  64.        String result = " ";
  65.  
  66.        for (int i= size-1; i >= 0; i--)
  67.        {
  68.            result += this.data[i] + " " ;
  69.        }
  70.  
  71.        return result;
  72.    }
  73.  
  74.  
  75.  
  76. }

Código
  1. package clientqueue;
  2. import java.util.logging.Level;  
  3. import java.util.logging.Logger;
  4.  
  5.  
  6.  
  7. public class ClientQueue {
  8.    public static void main(String[] args) {
  9.        Queue<String> myQueue = new Queue();
  10.        myQueue.push("Jesus");
  11.        myQueue.push("Alberto");
  12.        myQueue.push("Enrique");
  13.        myQueue.push("Isma");
  14.        myQueue.push("Alexis");
  15.        System.out.println(myQueue);
  16.  
  17.        try {
  18.            myQueue.pop();
  19.        } catch (Exception ex) {
  20.            Logger.getLogger(ClientQueue.class.getName()).log(Level.SEVERE, null, ex);
  21.        }        
  22.        System.out.println(myQueue);        
  23.  
  24.  
  25.    }    
  26.  
  27.  
  28. }


« Última modificación: 13 Febrero 2019, 17:39 pm por sheiking » En línea

ThunderCls


Desconectado Desconectado

Mensajes: 455


Coder | Reverser | Gamer


Ver Perfil WWW
Re: invertir cola
« Respuesta #1 en: 13 Febrero 2019, 18:35 pm »

Primer resultado en google  :¬¬

https://www.geeksforgeeks.org/reversing-a-queue/


En línea

-[ "…I can only show you the door. You're the one that has to walk through it." – Morpheus (The Matrix) ]-
http://reversec0de.wordpress.com
https://github.com/ThunderCls/
sheiking

Desconectado Desconectado

Mensajes: 10


Ver Perfil
Re: invertir cola
« Respuesta #2 en: 13 Febrero 2019, 19:35 pm »

amigo probe lo que me dices cree una clase llamada stack con sus metodos pero me sigue saliendo los mismos datos iguales

aqui esta el codigo
Código
  1. package clientqueue;
  2. import java.util.logging.Level;  
  3. import java.util.logging.Logger;
  4.  
  5.  
  6.  
  7. public class ClientQueue {
  8.    public static void main(String[] args) {
  9.        Queue<String> myQueue = new Queue();
  10.        myQueue.push("Jesus");
  11.        myQueue.push("Alberto");
  12.        myQueue.push("Enrique");
  13.        myQueue.push("Isma");
  14.        myQueue.push("Alexis");
  15.        System.out.println(myQueue);
  16.  
  17.        try {
  18.            myQueue.pop();
  19.        } catch (Exception ex) {
  20.            Logger.getLogger(ClientQueue.class.getName()).log(Level.SEVERE, null, ex);
  21.        }        
  22.        System.out.println(myQueue);    
  23.  
  24.        System.out.println("cola invertida: ");
  25.        myQueue.invert();
  26.        System.out.println(myQueue);
  27.  
  28.  
  29.    }    
  30.  
  31.  
  32. }

Código
  1. package clientqueue;
  2.  
  3. import java.util.logging.Level;
  4. import java.util.logging.Logger;
  5.  
  6.  
  7. public class Queue<E> {
  8.      public static final int CAPACITY  =100000;
  9.      private E[] data;
  10.      private int size=0;
  11.  
  12.      public Queue() {
  13.         this.data  = (E[])new Object[this.CAPACITY];
  14.      }
  15.  
  16.      public boolean isEmpty(){        
  17.         return (this.size==0);
  18.      }
  19.  
  20.      public int size(){
  21.  
  22.         return (this.size);
  23.    }
  24.  
  25.      public void push(E value){
  26.        this.data[this.size] = value;
  27.        this.size++;
  28.    }
  29.  
  30.      public E pop() throws Exception{
  31.        E result=null;
  32.        if (this.isEmpty()){
  33.            throw new Exception("La cola está vacía");
  34.    }
  35.        result = this.data[0];
  36.  
  37.      for (int i=0;i<this.size-1;i++){
  38.            data[i]=data[i+1];            
  39.        }
  40.        this.data[this.size]= null;
  41.        this.size--;        
  42.        return result;
  43.  
  44.      }
  45.      public E peek() throws Exception{
  46.  
  47.        E result=null;
  48.        if (this.isEmpty()){
  49.            throw new Exception("La Cola está vacía");
  50.        }
  51.        result = this.data[0];
  52.        return result;
  53.    }
  54.     public E peekLast() throws Exception{
  55.  
  56.        E result=null;
  57.        if (this.isEmpty()){
  58.            throw new Exception("La Cola está vacía");
  59.        }
  60.        result = this.data[size-1];
  61.        return result;
  62.    }
  63.  
  64.     @Override
  65.    public String toString()
  66.    {
  67.        String result = " ";
  68.  
  69.        for (int i= size-1; i >= 0; i--)
  70.        {
  71.            result += this.data[i] + " " ;
  72.        }
  73.  
  74.        return result;
  75.    }
  76.    public  void invert(){
  77.        Stack aux = new Stack();
  78.        Queue result = new Queue();
  79.        while(!result.isEmpty()){
  80.            try {
  81.                aux.push(result.peek());
  82.                result.pop();
  83.            } catch (Exception ex) {
  84.                Logger.getLogger(Queue.class.getName()).log(Level.SEVERE, null, ex);
  85.            }
  86.        }
  87.        while(!aux.isEmpty()){
  88.            try {
  89.                result.push(aux.peek());
  90.                aux.pop();
  91.            } catch (Exception ex) {
  92.                Logger.getLogger(Queue.class.getName()).log(Level.SEVERE, null, ex);
  93.            }
  94.        }
  95.  
  96.  
  97.    }
  98. }

Código
  1. package clientqueue;
  2.  
  3.  
  4. public class Stack<E> {
  5.    public static final int CAPACITY  =100000;
  6.      private E[] data;
  7.      private int size=0;
  8.      public Stack() {
  9.         this.data  = (E[])new Object[this.CAPACITY];
  10.    }
  11.  
  12.       public boolean isEmpty(){        
  13.         return  (this.size==0);
  14.      }
  15.  
  16.       public int size(){
  17.         return  (this.size);
  18.      }
  19.       public void push(E value){
  20.      this.data[this.size] = value;
  21.      this.size++;
  22.      }
  23.        public E  pop() throws Exception{
  24.        E  result = null;
  25.        if (this.isEmpty()){
  26.          throw  new Exception("La  Pila está vacía");
  27.        }
  28.        this.size--;
  29.        result = this.data[this.size];
  30.        this.data[this.size]= null;
  31.        return result;
  32.    }
  33.       public E  peek() throws Exception{
  34.        E  result = null;
  35.        if (this.isEmpty()){
  36.            throw  new Exception("La  Pila está vacía");
  37.        }
  38.        result = this.data[this.size];
  39.        return result;
  40.    }
  41.  
  42.  
  43.  
  44.  
  45. }
  46.  
En línea

EdePC
Moderador Global
***
Desconectado Desconectado

Mensajes: 2.067



Ver Perfil
Re: invertir cola
« Respuesta #3 en: 14 Febrero 2019, 00:53 am »

Saludos,

- Tamaño código :xD, con esto me funciona a mí, intenta injertarlo en tu código:

Código
  1. import java.util.*;
  2.  
  3. class ReverseQueue {
  4.  public static void main(String[] args) {
  5.    Queue<String> myQueue = new LinkedList();
  6.    myQueue.add( "Jesus" );
  7.    myQueue.add( "Alberto" );
  8.    myQueue.add( "Enrique" );
  9.    myQueue.add( "Isma" );
  10.    myQueue.add( "Alexis" );
  11.  
  12.    System.out.println( "\nCola tal cual" );
  13.    for ( String str : myQueue ) {
  14.      System.out.println( "\t" + str );
  15.    }
  16.  
  17.    // Reverse a la cola
  18.    Stack<String> stack = new Stack();
  19.    while ( !myQueue.isEmpty() ) {
  20.      stack.add( myQueue.peek() );
  21.      myQueue.remove();
  22.    }
  23.    while ( !stack.isEmpty() ) {
  24.      myQueue.add( stack.peek() );
  25.      stack.pop();
  26.    }
  27.  
  28.    System.out.println( "\nCola al revez" );
  29.    for ( String str : myQueue ) {
  30.      System.out.println( "\t" + str );
  31.    }
  32.  }
  33. }

Código:
c:\Users\EdSon\Desktop>javac ReverseQueue.java && java ReverseQueue
Note: ReverseQueue.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

Cola tal cual
        Jesus
        Alberto
        Enrique
        Isma
        Alexis

Cola al revez
        Alexis
        Isma
        Enrique
        Alberto
        Jesus

c:\Users\EdSon\Desktop>

-- Mmm..., me pone nervioso ese Unsafed Operations >:D

- Referencias: https://www.geeksforgeeks.org/reversing-a-queue/
En línea

CalgaryCorpus


Desconectado Desconectado

Mensajes: 323


Ver Perfil WWW
Re: invertir cola
« Respuesta #4 en: 23 Febrero 2019, 13:27 pm »

-- Mmm..., me pone nervioso ese Unsafed Operations >:D

Tienes que definir la linkedList y el Stack usando el diamond operator:

Código
  1. Queue<String> myQueue = new LinkedList<>();
  2. ...
  3. Stack<String> stack = new Stack<>();
  4.  
En línea

Aqui mi perfil en LinkedIn, invitame un cafe aqui
CalgaryCorpus


Desconectado Desconectado

Mensajes: 323


Ver Perfil WWW
Re: invertir cola
« Respuesta #5 en: 23 Febrero 2019, 13:38 pm »

amigo probe lo que me dices cree una clase llamada stack con sus metodos pero me sigue saliendo los mismos datos iguales

Creo que lo que explica que tu metodo invert() no funcione es esta:

1. El metodo invert que definiste crea una Queue de nombre result, que por supuesto originalmente esta vacia.
2. El primer ciclo no hace nada pues la cola esta vacia, por lo que el stack definido para la ocasion no se toca en absoluto.
3. El segundo ciclo no hace nada pues el stack esta vacio, por lo dicho anteriormente, y
4. luego no se hace nada con la cola result.
En línea

Aqui mi perfil en LinkedIn, invitame un cafe aqui
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
¿Invertir cadena?
PHP
yeikos 1 4,248 Último mensaje 10 Abril 2005, 05:18 am
por byebye
[T] Invertir saltos
Ingeniería Inversa
Erik# 1 2,798 Último mensaje 1 Enero 2009, 16:47 pm
por Amerikano|Cls
pasar datos de una cola dinámica a otra cola...
Programación C/C++
include (); 4 9,221 Último mensaje 10 Agosto 2012, 10:01 am
por BlackZeroX
invertir un vector en C
Programación C/C++
windic 7 36,486 Último mensaje 16 Septiembre 2018, 04:46 am
por Beginner Web
invertir una frase en C
Programación C/C++
lucho666 2 7,278 Último mensaje 17 Octubre 2014, 18:00 pm
por lucho666
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines