recursion function keeps running and prints nothing

只愿长相守 提交于 2020-04-30 08:37:06

问题


Long story short, I'm supposed to make a code that inserts, deletes, searches for and prints numbers in a skip list with the first node being negative infinity and the last node being positive infinity (-inf > (...) > inf). I called my search function from my insert function to find a spot to insert any new nodes (only after the third node has been inserted) and I initialize or reference my nodes outside the main function rather than inside of it (although I'm debating on whether or not I should do the latter instead). However one of my functions may be stuck in a loop.

static Node search(double item, double max) {
  Node head2 = head;
  head2 = Start(head2, max);
  //starts at the first highest node in the skiplist

  //{... } //find a specific node in a skiplist

  return head2;
}

//find first highest node for the search function
static Node Start(Node head2, double max) {
  System.out.println(head.key + " " + head.level);

  Node s = new Node();
  if (head2.max < max) {
    s = Start(head2.next, max);
    return s;
  }
  else if (head2.max >= max && head2.inf == false) {
    if (head2.level < head2.max) {
      s = Start(head2.up, max);
      return s;
    }
    else if (head2.level == head2.max) {
      s = head;
      return s;
    }
  }
  return s;
}

The start function is called from the search function (called in order of main > double insert > Node search > Node start) and it is supposed to find the first node of the highest level. Once it does so, It returns that node to the search function so it can start it's search from there. But when called, it simply goes blank and nothing happens despite continuing to run. When I put in a print function to determine the problem, it simply prints the first node's key and 1st level and goes blank from there. UPDATE: I've learned that the function is able to find the node but it can't return it via recursion. I would like to find a way to fix that.


回答1:


The problem was actually in my search function.

for(j = max; j >= 1; j--) {
            while(head2.next != last && head2.key != item && i == 0) {
                if(item > head2.key && head2.next != last) {
                    head2 = head2.next;
                }
                else if(item < head2.key || head2.next == last) {
                    head2 = head2.prev;
                    i = 1;
                }
            }
 (...)}

this was the function that kept looping so I had to change the statement for while by having it say this instead while(head2.next != last && head2.key < item && head2.inf != true && i == 0)



来源:https://stackoverflow.com/questions/60644504/recursion-function-keeps-running-and-prints-nothing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!