I'm trying to figure out how i can show all numbers in the stack i have, to do search method without using library. For example
if(value = allNumbers){
return true;
}
else{
return false;
}
The problem is I can't find the correct method how to display allNumbers
in the stack
My code:
public class Stack <T>{
private Item<T> q=null;
public boolean isEmpty() {
return q==null;
}
public void push(T d) {
Item<T> tmp=new Item<T>(d);
tmp.next=q;
q=tmp;
}
public T pop() {
if (isEmpty())
return null;
T tmp=q.data;
q=q.next;
return tmp;
}
public T peek(){
if (isEmpty())
return null;
T tmp = q.data;
return tmp;
}
// public boolean search (T value) {
// if(value == null ) {
// return false;
// }
// else{
// value = allNumbers ;
// return true;
// }
//
// }
}
Driver code:
public class Driver {
public static void main(String[] args) {
Stack<Integer> s=new Stack<Integer>();
int value = 2;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
s.push(6);
s.push(7);
s.push(8);
s.push(9);
System.out.println("Popped: " s.pop());
System.out.println("Last number put in is: " s.peek());
// System.out.println("Searching for: " );
// System.out.println("Is found: " s.search(9));
while (!s.isEmpty()) {
System.out.println(s.pop());
}
}
}
CodePudding user response:
I would assume your 'Item' class is custom since you haven't added any imports. The solution with that in mind is to add a method that takes in one parameter (data) and traverses all the items in the "q" list. If an item matches the data, return true. If not, return false. Also, remember to implement the 'equals()' method appropriately in the 'Item' class.
The implementation of the search method should be pretty much this:
public boolean search(T value) {
if (value == null) {
return false;
}
Item<T> item = q;
while (q != null) {
if (q.equals(value))
return true;
}
return false;
}