0

I have a question about a stack. Generally, I will define the push method in the easiest way like

 Int size;
 public void push(int value){
    elements[size++] = value;}

If I’d like to push the integer in an increasing order and invoke pop method in a decreasing order, how could I define this method inside the same push method?

Mat
  • 202,337
  • 40
  • 393
  • 406
Cooky Kao
  • 43
  • 1
  • 2
  • 6
  • Can you explain more? My opinion is that you are writing about LIFO (last in first out) structure - that's a stack, when you put 1, 2, 3, 4 to it, you want to get 4, 3, 2, 1, so your pop is `return elements[size--];`. – Betlista Apr 26 '12 at 08:27

4 Answers4

1

You dont have sorting facility in Stack.
Better way is that, sort your data in ascending order before you push it into the stack. And while popping the data from stack, you will get data in descending order.

Sachin Mhetre
  • 4,465
  • 10
  • 43
  • 68
0

The it doesnt remain a stack try sorted list

and get the first element and delete it during the pop.

Community
  • 1
  • 1
Nitin Chhajer
  • 2,299
  • 1
  • 24
  • 35
0

Use a sorted collection to store the data instead of a plain array. You can find suggestions on creating a sorted list here.

Community
  • 1
  • 1
Raam
  • 10,296
  • 3
  • 26
  • 27
-1

A stack typically is a LIFO data structure. If you are looking for some ordered collection, look at SortedSet.

Snicolas
  • 37,840
  • 15
  • 114
  • 173