我正在尝试在 Java 中实现一个链表样式堆栈(不使用内置的明显方式)。push 操作很简单,但是 pop 操作很麻烦。我很清楚,将“弹出”值返回给调用者并同时调整链表会很有用,但这似乎不起作用。
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);
}
}