我尝试使用递归计算队列中的索引数。队列是一个列表,它由" queue“类中的函数组成。我现在拥有的是一个函数,它可以计算索引的数量,也可以删除它们。我什么都试过了,但还是没有成功,所以我请求你们的帮助。我必须补充的是,如果您看到一个以大写字母开头的函数,请忽略它,并表现得像它不是以大写字母开头一样,Thx!:)
public class Queue<T>
{
private Node<T> first;
private Node<T> last;
public Queue()
{
this.first = null;
this.last = null;
}
public void Insert(T x)
{
Node<T> temp = new Node<T>(x);
if (first == null)
first = temp;
else
last.setNext(temp);
last = temp;
}
public T Remove()
{
T x = first.getValue();
first = first.getNext();
if (first == null)
last = null;
return x;
}
public T Head()
{
return first.getValue();
}
public boolean IsEmpty()
{
return first == null;
}
public String toString()
{
String s = "[";
Node<T> p = this.first;
while (p != null)
{
s = s + p.getValue().toString();
if (p.getNext() != null)
s = s + ",";
p = p.getNext();
}
s = s + "]";
return s;
}
}
public class Node<T>
{
private T value;
private Node<T> next;
public Node(T value)
{
this.value = value;
this.next = null;
}
public Node(T value, Node<T> next)
{
this.value = value;
this.next = next;
}
public T getValue()
{
return value;
}
public Node<T> getNext()
{
return next;
}
public void setValue(T value)
{
this.value = value;
}
public void setNext(Node<T> next)
{
this.next = next;
}
public String toString()
{
return this.value+ " " +next;
}
}//Class
public class Main {
public static void main(String[] args) {
Queue<Integer> q = new Queue<Integer>();
q.Insert(1);
q.Insert(2);
q.Insert(3);
q.Insert(4);
System.out.println("Queue: " + q);
countIndex(q);
System.out.println("Queue after the function: " + q);
}
public static int countIndex(Queue<Integer> q) {
if(q.Head() == null) return 0;
q.Insert(q.Remove());
return 1 + countIndex(q);
}
}//class发布于 2020-09-15 10:07:12
我不知道为什么一定要使用递归,但这里有两个用于Queue类的方法,它们使用递归并返回链表(Queue)中的节点数:
private int rsize(Node<T> p) {
if (p == null)
return 0;
return rsize(p.getNext()) + 1;
}
public int size() {
return rsize(first);发布于 2020-09-15 21:24:06
没有gurantees,但像这样的东西应该可以:
public static int countIndex(Queue<Integer> q) {
return countIndex(q, new Queue<Integer>());
}
private static int countIndex(Queue<Integer> q,
Queue<Integer> temp)
{
int size = 0;
if(q.Head() != null) {
temp.Insert(q.Remove());
size = 1 + countIndex(q, temp);
q.Insert(temp.Remove());
}
return size;
}https://stackoverflow.com/questions/63893876
复制相似问题