CS 112 Lab 2

Agenda

We will consider the stack ADT and implement sorting using only stack operations (push, pop, peek and isEmpty).

Today's example

package lab01;
import java.util.*;

public class StackTest {
	
	public static void main( String [] args )
	{
		
		Stack<Integer> stackA = new Stack<Integer>();
		Stack<Integer> stackB = new Stack<Integer>();
		Stack<Integer> stackC = new Stack<Integer> ();
		
		Random rand = new Random();
		
		for( int i = 0 ; i < 20; i++ )
		{
			stackA.push(new Integer(rand.nextInt(1000)));
		}
		
		// Example: transfer element from stackA to stackB
		// stackB.push( stackA.pop() );
		
		// Example: compare element at top of stackA to top of stackB
		//if( stackA.peek() < stackB.peek() )
	
		// Goal: transfer elements from stackA to stackC in sorted order
		// using only stack operations: push, pop, peek and isEmpty
		while( !stackA.isEmpty() )
		{
			//Step 1
			stackB.push( stackA.pop() );
			
			//Step 2
			while( !stackC.isEmpty() && stackC.peek() < stackB.peek() )
			{
				stackA.push( stackC.pop() );
			}
			
			//Step 3
			stackC.push( stackB.pop() );
			
			//Step 4
			while( !stackA.isEmpty() && stackA.peek() < stackC.peek() )
			{
				stackC.push( stackA.pop() );
			}
		}
		
		//Print the elements in stackC
		for( int i = stackC.size()-1; i >=0 ; i-- )
			System.out.println(stackC.get(i));	
	}
}
	  

URL

http://cs-people.bu.edu/tvashwin/cs112_spring08/lab03.html