我现在只是在 Java 中闲逛,尝试使用链表实现类似于堆栈的东西。
class ListStack {
int value;
int size;
ListStack next;
public ListStack (int add) {
this.size = 1;
this.value = add;
this.next = null;
}
public void push (int add) {
this.next = this;
this.value = add;
this.size++;
}
public int pop() {
if (this.size == 0) { throw new EmptyListStackException(); }
int i = this.value;
this = this.next;
this.size--;
return i;
}
public int size() {
return this.size;
}
public int peek() {
return this.value;
}
}
基本上它是一个前面插入的链表,也从前面删除。当我尝试执行以下操作时,NetBeans 弹出错误:
this = this.next
;它说我无法重新分配最终值this
。
我希望我的最终实现能够执行如下操作:
ListStack var = new ListStack(5); //var is now 5 -> null
var.push(3); //var is now 3 -> 5 -> null
int val = varr.pop(); //var is now 5 -> null, val == 3
评论放置
this = this.next
代码,其余的似乎可以工作。
ListStack a = new ListStack(5);
System.out.println(a.size()); //prints 1
System.out.println(a.peek()); //prints 5
a.push(4);
System.out.println(a.size()); //prints 2
System.out.println(a.peek()); //prints 4
a.push(6);
System.out.println(a.size()); //prints 3
System.out.println(a.peek()); //prints 6
a.push(1);
System.out.println(a.size()); //prints 4
System.out.println(a.peek()); //prints 1
//a is 1 -> 6 -> 4 -> 5 -> null
您的代码中存在概念错误:基本上您没有使用 Push 方法创建任何新的堆栈元素。
但问题是调用类 listStack 会产生误导,因为实际上您要创建的是堆栈的新元素,因此您也许应该创建一个类节点。 此外,你不能 ovveride “this”,因为它是一个 java 关键字,并且它总是引用当前对象。
为了给您提示如何将堆栈实现为链表,您应该创建带有值字段
class Node
的 value
以及对前一个 Node
的引用(第一个节点只有一个空指针) .
在类
ListStack
中,您应该有对最后一个节点的引用,并且其 push()
方法应该创建一个新节点并将其设置为新的最后一个节点。
让我为您指明正确的方向。正如其他人评论的那样,这个堆栈无法正常工作考虑做这样的事情:
public class ListStack {
private class Node {
private int value;
private Node next;
//inner class which holds your each element and reference to next
//fill all details required
}
private Node head;
private int size;
public ListStack() {
head = null;
size = 0;
}
public void push(int value) {
Node temp = new Node(value);
if(head == null)
head = temp;
else {
temp.setNext(head); // provide link to already existing stack
head = temp; // bring new element on top
}
}
public int pop() {
if(head==null);
//throw exception
int temp = head.getValue();
head = head.getNext(); //remove element and bring down the stack
return temp;
}
}
英语不是我的母语;请原谅打字错误或语法错误。
这是我的第一个回答,可能不正确,仅供参考。
在我看来,您可以更改您的
push
和 pop
类以使其正常工作。说实话,修改后的 pop
类不是一个好的答案,您应该像其他人提到的那样更改您的 ListStack
类上面的内容可以使您的链接列表正常工作。
public int pop() {
if (this.size == 0) { throw new EmptyListStackException(); }
if (this.size == 1) { return this.value;}
int i = this.value;
this.value = this.next.value;
this.next = this.next.next;
this.size--;
return i;
}