user3052940
user3052940

Reputation: 15

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

Upvotes: 0

Views: 3796

Answers (2)

BatScream
BatScream

Reputation: 19700

As @ColonelThirtyTwo mentioned in the comments,

if(stack.size() >= 2)
{
    T first = stack.pop();
    T second = stack.pop();
    stack.push(first);
    stack.push(second);
}

Upvotes: 2

Gil Vegliach
Gil Vegliach

Reputation: 3562

  • 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.

Upvotes: 0

Related Questions