具有插入和删除预定义的链接列表的mergeTo函数

时间:2015-02-04 01:32:35

标签: java linked-list

好的,所以我对mergeTo函数有点问题,该函数应该将两个链接列表合并为一个(这个和那个链接列表 - 合并到这里)。这是mergeTo的代码:

public void mergeTo(WordLinkedList that){

   Node current = that.firstnode;
   int i = 0;

   while (current != null){ //iterating through all the elements of 'that' list
       this.insert(current.word);//inserting each successive word into 'this'
       that.remove(i); //removing each successive word from 'that'
       current = current.next;//moving the pointer forward
       i++; //moving the counter forward (for the remove function
   }
}

我对该函数的逻辑只是遍历该链表的每个元素 - 将每个连续元素插入'this'列表然后立即删除它(使用i作为计数器)

这是我的插入功能:

public void insert(String newword){

  Node newNode = new Node(newword);
  size++;
  Node previous = null;
  Node present = firstnode;

  while ((present != null)&& (newword.compareTo(present.word) > 0)){
      previous = present;
      present = present.next;
  }
  if (present != null && newword.compareTo(present.word)==0){
      size--;
      return;
  }
  if ((previous == null)){
      firstnode = newNode;
  }
  else{
      previous.next = newNode;
  }
  newNode.next = present;
}

我的插入功能应该在我的链表中插入内容,同时保持字母顺序。我测试了它,我认为它按预期工作。我不相信它有任何问题。

这是我的删除功能:

public String remove (int i){
   Node present = firstnode;
   Node previous = firstnode;

   if (i > this.size || i < 0)
       throw new IndexOutOfBoundsException("Hahahahahahaha it's out of bounds!!!!!!!!");

   if (i == 0 && firstnode != null){
       firstnode = firstnode.next;
   }
   else{
   for (int j = 0; j < i; j++){
       present = present.next;
   }
   for (int k = 0; k < i-1; k++){
       previous = previous.next;
   }

   previous.next = present.next;
   present.next = null;
   size--;
   }
   return present.word;
}

我对此进行了测试,对于我的测试用例,它工作正常,但我认为问题出在remove函数中。如果我从mergeTo方法中注释掉删除行 - 插入工作正常。但是,如果我把它留在那里,它会产生一些意想不到的行为。这是我的测试功能:

    String[] words6={"eta","gamma", "zeta"};//to test mergeTo
    String[] words7={"alpha","beta","phi"};//to test mergeTo - no common    words with words6
    listObj1=new WordLinkedList(words6);
    listObj2=new WordLinkedList(words7);
    listObj1.mergeTo(listObj2);
    System.out.println("this list: \n"+listObj1.toString());
    System.out.println("size of this list = " + listObj1.getSize());
    System.out.println("that list: \n"+listObj2.toString());
    System.out.println("size of that list = " + listObj2.getSize());

我的假设输出: 测试17 - mergeTo 这个清单: α 公测 ETA 伽马 披 泽塔 此列表的大小= 6 那个清单: 该列表为空 该列表的大小= 0

我的实际输出: 这个清单: α 公测 ETA 伽马 泽塔 此列表的大小= 5 那个清单: 公测 该列表的大小= 2

1 个答案:

答案 0 :(得分:0)

好的,所以我想出了如何解决问题:)。在mergeTo方法中,that.remove(i)应更改为that.remove(0) - remove方法每次都会删除第一个索引。