2016-02-20 54 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。