2016-02-20 68 views
0
static Stack<Integer> sort(Stack<Integer> s){ 
    Stack<Integer> auxiliar = new Stack<Integer>(); 
    int e; 
    if(!s.isEmpty()) auxiliar.push(s.pop()); 
    while (!s.isEmpty()){ 
      e=s.peek(); 
      if(e>auxiliar.peek() && e<s.peek()) 
        auxiliar.push(e); 
      else if ((e>auxiliar.peek() && e>s.peek())|| (e<auxiliar.peek() &&  
      e>s.peek())){              
       auxiliar.push(s.pop()); 
       s.push(e); 
       s.push(auxiliar.pop()); 
     } 
     else if (e<auxiliar.peek()&&e<s.peek()){ 
       s.push(auxiliar.pop()); 
       s.push(e); 
     } 
     else auxiliar.push(e); 
    } 
    return auxiliar; 
} 

void printStack(Stack<Integer> s){ 
    System.out.print("["); 
    while (!s.isEmpty()){ 
     System.out.print(s.pop()+" "); 
    } 
    System.out.print("]"); 
} 

public static void main(String[] args) { 
    Stack<Integer> a = new Stack<Integer>(); 
    a = {2,3,8,6,4}; //In this line I do not know how to give values to the stack. 
    // I don't know if I have to make a function outside of main or if 
    // I can do it like I was trying 

    SortedStack element = new SortedStack(); 
    element.sort(a); 
} 

回答

2

一种方法将值添加到堆栈中创建主堆栈与整数值是这样的:

Stack<Integer> s = new Stack<>(); 
    s.addAll(Arrays.asList(2, 3, 4, 6, 4)); 

使用这种方法,它会为了推动左到右边,所以4将在堆栈顶部,在底部2。