简体   繁体   中英

how to swap stacks element in java

I want to do a swap to the two tops element in a stack I tried, but can not figure it out

public void swap(){

 T temp=stack[topIndex];
 stack[topIndex]=stack[stack.length-1];
 stack[stack.length-1]=temp;


 }

topindex is already defined in superclass

As @ColonelThirtyTwo mentioned in the comments,

if(stack.size() >= 2)
{
    T first = stack.pop();
    T second = stack.pop();
    stack.push(first);
    stack.push(second);
}
  • You are mixing up topIndex with stack.length

It seems you are using an array to implement a stack. In this case the code to swap two top elements is the same as for swapping two elements in an array:

T temp = stack[topIndex];
stack[topIndex] = stack[topIndex - 1];
stack[topIndex - 1] = temp;

You can implement this also popping two elements and pushing them back in the opposite order. Adding a check if you have at least two elements is also a good idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM