开发者

search method in Stack class

I am using Stack class in Java. But the search method is not working..

Here is the code i am using with elements in temps array is d b a g e c b:

开发者_运维知识库 int x=0,y=0;
 ss.setSize(50);
      ss.push(temps[x]);
      System.out.print(temps[x]);
      ss.push(1);
      System.out.println(" 1");
      for(x=1;x<z;x++){
          if((y=ss.search(temps[x]))>=0){
               System.out.println("Hi......from the search");
          }
        else{
        ss.push(temps[0]);
        System.out.print(temps[x]);
        ss.push(1);
        System.out.println(" 1");
       }
      }


Step through your code and you'll notice the only items being put on the stack are 'd' and 1. Also, the only items you are searching for are 'b', 'a', 'g', 'e', and 'c'. So, search will always return -1.

In short, search is working fine and your code logic is not totally correct.


Looks to me you want a Stack that doesn't store duplicates.

There's one suspicious line:

else{
    ss.push(temps[0]);  // <--- this should be temps[x]


The logic is wrong. It should be something similar to -

while length is 0 to temps_length-1 // length increments by 1 at each iteration

    variable returnValue Equals to stack.search(temps[length])

    if returnValue Equals To -1
       Add Element to the Stack if the stack is not full

    else
       Element found on the stack

    end if

End while
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜