Observando o Código, o que ele quer fazer?

8 respostas
Jonas_backer

Observando o Código, o que ele quer fazer ?

import java.util.ArrayList;

public class Stack< T >
{
private ArrayList< T > elements; 

	public Stack()
	{
		this( 10 ); // default stack size
	} // end no-argument Stack constructor
	
		// constructor creates a stack of the specified number of elements
	public Stack( int capacity )
	{
		int initCapacity = capacity > 0 ? capacity : 10; // validate
		elements = new ArrayList< T >( initCapacity ); // create ArrayList
	} // end one-argument Stack constructor
	
		// push element onto stack
	public void push( T pushValue )
	{
	    elements.add( pushValue ); // place pushValue on Stack
	} // end method push
	
		// return the top element if not empty; else throw EmptyStackException
	public T pop()
		{
		if (elements.isEmpty()) // if stack is empty
		throw new EmptyStackException( "Stack is empty, cannot pop" );
	
		// remove and return top element of Stack
		return elements.remove( elements.size() - 1 );
		} // end method pop
	 } // end class Stack< T >
public class EmptyStackException extends RuntimeException
{
	public EmptyStackException()
	{
		this("Stack is empty");
	}
	public EmptyStackException(String message)
	{
		super(message);
	}
}
public class StackTest
 {
		public static void main( String[] args )
		{
		double[] doubleElements = { 1.1, 2.2, 3.3, 4.4, 5.5 };
		int[] integerElements = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

		// Create a Stack< Double > and a Stack< Integer >
		Stack< Double > doubleStack = new Stack< Double >( 5 );
		Stack< Integer > integerStack = new Stack< Integer >();

		// push elements of doubleElements onto doubleStack
		testPushDouble( doubleStack, doubleElements );
		testPopDouble( doubleStack ); // pop from doubleStack

		// push elements of integerElements onto integerStack
		testPushInteger( integerStack, integerElements );
		testPopInteger( integerStack ); // pop from integerStack
		} // end main

 
	// test push method with double stack
	private static void testPushDouble(
	Stack< Double > stack, double[] values )
	{
	System.out.println( "\nPushing elements onto doubleStack" );

	// push elements to Stack
	for ( double value : values )
	{
	System.out.printf( "%.1f ", value );
	stack.push( value ); // push onto doubleStack
	} // end for
	} // end method testPushDouble

	// test pop method with double stack
	private static void testPopDouble( Stack< Double > stack )
	{
	// pop elements from stack
	try
	{
	System.out.println( "\nPopping elements from doubleStack" );
	double popValue; // store element removed from stack

	// remove all elements from Stack
	while ( true )
	{
	popValue = stack.pop(); // pop from doubleStack
	System.out.printf( "%.1f ", popValue );
	} // end while
	} // end try
	catch( EmptyStackException emptyStackException )
	{
	System.err.println();
	emptyStackException.printStackTrace();
	} // end catch EmptyStackException
	} // end method testPopDouble

	// test push method with integer stack
	private static void testPushInteger(
	Stack< Integer > stack, int[] values )
	{
	System.out.println( "\nPushing elements onto integerStack" );

	// push elements to Stack
	for ( int value : values )
	{
	System.out.printf( "%d ", value );
	stack.push( value ); // push onto integerStack
	}//endfor
} // end method testPushInteger
 // test pop method with integer stack
private static void testPopInteger( Stack< Integer > stack ) {
			// pop elements from stack
			try
			{
			System.out.println( "\nPopping elements from integerStack" );
			int popValue; // store element removed from stack
			
			// remove all elements from Stack
			while ( true )
			{
			popValue = stack.pop(); // pop from intStack
			System.out.printf( "%d ",	popValue );
			} // end while
			} // end try
			catch( EmptyStackException emptyStackException )
			{
			System.err.println();
			emptyStackException.printStackTrace();
			} // end catch EmptyStackException
		}	// end method testPopInteger
	}	//	end class StackTest

8 Respostas

A

É um exercício de implementação de pilha, demonstrando o empilhamento e desempilhamento de itens.

Jonas_backer

Se eu fosse materializar esse código pra uma finalidade , que aplicação eu teria.

A

Uma aplicação prática por exemplo poderia ser resolução de fórmulas. Imagine que você tivesse uma string representando uma expressão aritmética: 10 + 45 / 5. São três operandos (os números) e dois operadores( + e / ). Você poderia empilhar esses cinco elementos e a cada ciclo de desempilhamento de um operando, um operador e outro operando você resolveria a operação e guardaria o resultado. Pegaria o próximo ciclo até que esvaziasse a pilha quando então retornaria o resultado final.

Isso é coisa que se vê quando se estuda estruturas de dados. A pilha é um tipo de estrutura, a fila é outro… e por aí vai

Jonas_backer

ADEMILTON:
Uma aplicação prática por exemplo poderia ser resolução de fórmulas. Imagine que você tivesse uma string representando uma expressão aritmética: 10 + 45 / 5. São três operandos (os números) e dois operadores( + e / ). Você poderia empilhar esses cinco elementos e a cada ciclo de desempilhamento de um operando, um operador e outro operando você resolveria a operação e guardaria o resultado. Pegaria o próximo ciclo até que esvaziasse a pilha quando então retornaria o resultado final.

Isso é coisa que se vê quando se estuda estruturas de dados. A pilha é um tipo de estrutura, a fila é outro… e por aí vai

Estou colando mais algumas informações, se tiver mais exemplos só colocar , Thanks !!!

Some of the applications related to computer science using Stack

Stack data structure are used for implementing normal as well as recursive function calls and to store local variables which are declared inside a method
Evaluation of expressions / syntax Parsing
Validating and parsing XML
Converting a decimal number into a binary number , decimal to octal , etc …
Towers of Hanoi
QuickSort
Undo sequence in a text editor
Pages visited history in a Web browser
and more …

Jonas_backer

[b]Stack é uma classe antiga do Java. Ela é da mesma idade do Vector e do Hashtable.

Atualmente usa-se LinkedHashSet, que além de lista encadeada também pode ser usada como pilha (LIFO).

[/b]

Jonas_backer

Talvez a mesma mecânica

import java.util.Iterator;
import java.util.LinkedHashSet;

public class LinkedHashSetExample {

    /**
     * LinkedHashSet example
     * Adding/removing objects to the LinkedHashSet and basic LinkedHashSet methods
     */
    public static void main(String[] args) {
        LinkedHashSet<String> set = new LinkedHashSet<String>();
        set.add("First");
        set.add("Second");
        set.add("Third");
        set.add("Fourth");
        set.add("Fifth");
        System.out.println("Set elements:");
        for(String s : set){
            System.out.println("-" + s);
        }
        System.out.println("Set size:" + set.size());
        System.out.println("Removing element 'Third'...");
        set.remove("Third");
        System.out.println("Set size:" + set.size());
        System.out.println("Set elements:");
        //iterating by iterator
        Iterator<String> i = set.iterator();
        while (i.hasNext()) {
            String s = i.next();
            System.out.println("-" + s);
        }
        System.out.println("Set contains object 'First'? "
                + set.contains("First"));
       
        System.out.println("Removing all elements...");
        set.clear();
        System.out.println("Set is empty now? " + set.isEmpty());
        set.add(null);
    }
}
lina

Oi,

Onde você quer chegar com isso? Tudo isso não passa de uma Estrutura de dados Clássica (meios de armazenamento e organização de dados de modo que possam ser usados eficientemente).

Tchauzin!

Jonas_backer

lina:
Oi,

Onde você quer chegar com isso? Tudo isso não passa de uma Estrutura de dados Clássica (meios de armazenamento e organização de dados de modo que possam ser usados eficientemente).

Tchauzin!

Evolução das estruturas de dados e suas complexidades, se observamos os códigos temos ai uma radical mudança de implementação de usar Stacks e LinkedHastSet.

Criado 13 de junho de 2012
Ultima resposta 14 de jun. de 2012
Respostas 8
Participantes 3