I am attempting to implement a linked list style stack in Java (without using the built in obvious ways). The push operation is straightforward, but the pop operation is vexing. It is clear to me that it would be useful to return the "popped" value to the caller, and also adjust the linked list at the same time, but this does not seem to work.
public class ListElement {
/* constructor */
public ListElement(Integer data) {
value = data;
}
/* next pointer and the data */
private ListElement next;
private Integer value;
/* gets the next element */
public ListElement getNext() {
return next;
}
/* gets the data */
public Integer getValue() {
return value;
}
/* sets the next element */
public void setNext(ListElement elem) {
next = elem;
}
/* sets the data */
public void setValue(Integer data) {
value = data;
}
/* prints out the list */
public void printList(ListElement head) {
String listString = "";
ListElement elem = head;
while (elem != null) {
listString = listString + elem.getValue().toString() + " ";
elem = elem.getNext();
}
System.out.println(listString);
}
/* inserting at the front */
public ListElement push(ListElement head, Integer data) {
ListElement elem = new ListElement(data);
elem.setNext(head);
return elem;
}
/* pop the first element */
public Integer pop (ListElement head){
Integer popped = head.getValue();
head = head.getNext();
return popped;
}
public static void main(String[] args) {
System.out.println("Constructing List with 2 ...");
ListElement myList = new ListElement(2);
myList.printList(myList);
System.out.println("Adding 1 to beginning ...");
myList = myList.push(myList, 1);
myList.printList(myList);
System.out.println("Adding 0 to beginning ...");
myList = myList.push(myList, 0);
myList.printList(myList);
System.out.println("Pop ...");
Integer popped = myList.pop(myList);
System.out.println("Value is " + popped);
myList.printList(myList);
}
}