I'm implementing stacks in Java using linked lists and I'm still a beginner in programming.
I want to push an element into the stack but I'm getting this result, how do I solve it:
" Stack@15db9742 "
And this is my code:
public class Stack {
class Element{
int data;
Element next = null;
Element(int value){
data = value;
next = null;
}
}
private Element head = null;
public Stack() {
head = null;
}
public boolean isEmpty() {
return this.head == null;
}
public void push(int value) {
Element tmp = new Element(value);
tmp.next = head;
head = tmp;
}
public void pop() {
if(isEmpty())
System.exit(1);
head = head.next;
}
public int stackTop() {
if(isEmpty())
System.exit(2);
return head.data;
}
@Override
public String toString() {
return "Stack [head=" + head + "]";
}
public void makeEmpty() {
}
public int search(int value) {
if(isEmpty())
return -1;
Element cur = head; // cur = cursor
int n = 0;
while(cur != null) {
if(cur.data == value)
return n;
cur = cur.next;
n++;
}
return n;
}
public static void main(String[] args) {
Stack s1 = new Stack();
s1.push(1);
s1.push(2);
s1.push(3);
s1.push(4);
s1.push(5);
System.out.println(s1.toString());
}
}
I would like also a hint if the "search" method is correct. I just can't tell if it's working before solving my initial problem.