为JavaDJ中的LinkedList编写get方法

问题描述

我有一个 Java缩小(DJ)程序,该程序应执行以下操作:

理想的功能是让程序在用户输入自然数时输入自然数, 直到用户输入零为止。将这些数字视为存储在数组A中,第一个 输入的数字存储在A [0]中,第二个数字存储在A [1]中,依此类推。用户输入第一个0后, 您的程序将输入两个更多的自然数i和j,然后输出商和 A [i]除以A [j]时的余数。如果用户输入的A或i值超出A的范围(对于 例如,如果A的最后一个元素存储在A [5],但用户输入i作为i)值,则您的程序需要 为商和余数打印0。您可能会假设用户存储的内容永远不会超过 10,000个数字变成A。

期望行为的示例:

Enter a natural number: 7
Enter a natural number: 2
Enter a natural number: 0
Enter a natural number: 0
Enter a natural number: 1
3 1
(Here A[0]=7 and A[1]=2,so A[0]/A[1] has quotient 3 and remainder 1)

我的问题是编码get方法来获取索引处的元素。 LinkedList 已添加,因此其顺序相反,我不确定如何为它编写方法。我需要使用while循环。

代码:

class LinkedList extends Object {
  nat data;
  LinkedList next;

  nat setData(nat newData) {
    data = newData;
  }

  nat prepend(nat newData) {
    LinkedList currList;
    currList = new LinkedList();
    currList.data = data;
    currList.next = next;
    data = newData;
    next = currList;
    0;
  }
  // Problem method
  nat get(nat index) {
    LinkedList temp;
    temp = new LinkedList();

    while(temp != null && index >= 0) {
      temp = temp.next;
    }
    temp.data;
  }
}

// Method to divide because we can't do that
nat divide(nat a,nat b)
{
  if( b == 0 ) { 0; }

  else if(a-b == 0) { 1; }

  else if( a < b) { 0; }

  else { ( 1 + divide(a-b,b) ); };
}

// Method to find remainder because we can't do that either
nat remainder(nat a,nat b) {
  if(a < b) { b; }
  else { remainder(a - b,b) };
}

main {
  nat input;
  nat total;
  nat i;
  nat j;

  LinkedList ll;
  ll = new LinkedList();

  input = readNat();
  ll.setData(input);
  total = total + 1;
  while( !(input==0) ) {
    input = readNat();
    ll.prepend(input);
    total = total + 1;
  };

  // While loop ends when user has entered 0. We will now prompt for i and j.
  i = readNat();
  i = total - i;
  j = readNat();
  j = total - j;

  nat remainder = remainder(ll.get(i),ll.get(j));
  nat quotient = divide(ll.get(i),ll.get(j));

  printNat(quotient);
  printNat(remainder);
}

如果您发现代码有任何问题,请随时在注释中指出。我会很感激的(尽管这不是我要的)。精简的Java就像Java,只是将int替换为nat,它也没有那么多的功能,所以如果我做的是非常规的事情,那可能就是原因。

即使您不完全了解DJ,也希望这个问题仍然可以回答。我什至会接受Java的答案,然后将其翻译为DJ。它们是如此相似。这是一个Web文档,它对DJ进行了更多解释:https://www.cse.usf.edu/~ligatti/compilers-15/as1/dj/DJ-definition.pdf

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)