[英]Java: return self-made stack size using recursion
因此,當我注意到我上交的某個內容時,我已經遍歷了我在課堂上所做的一些作業。其中一部分是編寫堆棧和節點類,該類應該具有返回堆棧當前大小的方法。 我錯過了實際上需要在size方法中使用遞歸的事實。 因此,我嘗試了一些事情,並獲得了正確的結果。 這是代碼:
public class CharStack {
private CharStackNode top;
public CharStack() {
top=null;
}
public void push(char img) {
CharStackNode node=new CharStackNode(img, top);
top=node;
}
public char pop() {
char result = top.getImage();
top = top.getNext();
return result;
}
public char peek() {
return top.getImage();
}
public int size() {
int counter=0;
if(this.top!=null) {
counter=this.top.size();
}
return counter;
}
public boolean empty() {
return top == null;
}
}
如您所見,我正在調用節點的size方法來實際確定大小。 這是節點類:
public class CharStackNode {
private char image;
private CharStackNode next;
public CharStackNode(char image, CharStackNode next) {
this.image = image;
this.next = next;
}
public char getImage() {
return image;
}
public CharStackNode getNext() {
return next;
}
public int size() {
int count=0;
if(this.next!=null) {
count=this.next.size();
}
count+=1;
return count;
}
}
如您所見,我正在節點的size方法中執行遞歸部分。 但是,分配基本上意味着不要在節點類中使用額外的大小方法(不過我可以使用所有其他方法)。 我的問題是-我仍然不知道如何在仍使用遞歸的同時以其他方式實現它。
在此先感謝您的幫助。
您可以在堆棧類的私有方法上實現所需的遞歸,並且size()
方法僅用作前端。 這將允許您定義控制遞歸所需的任何參數。 例如,您可以實現類似以下的遞歸方法:
private int tailSize(CharStackNode from) {
return (from == null) ? 0 : (1 + tailSize(from.getNext()));
}
並將您的CharStack.size()
寫為
public int size() {
return tailSize(top);
}
請注意,遞歸是解決此特定問題的一種糟糕方法。 迭代解決方案的開銷較小,並且並不是特別復雜:
public int size() {
int rval = 0;
for (CharStackNode next = top; next != null; next = next.getNext()) {
rval += 1;
}
return rval;
}
您可以從您自己的堆棧類而不是從節點類調用遞歸函數。 可以使用循環而不是遞歸來獲取大小。
使用您的代碼從堆棧中調用(以top
作為參數進行調用):
public int size(CharStackNode node) {
// check to see if this node is null
if (node == null) {
return 0;
}
// call this function with the next node as the parameter
tempInt = size(node.getNext());
return tempInt + 1;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.