尝试在链表中的第 3 个位置插入节点 java

Trying to insert node at 3rd position in linkedlist java

所以就像标题说的那样,我正在尝试在链表的第三个位置输入一个节点。我最初尝试这样做的方法是在 numberOfItems >= 3 之后在列表中插入两个位置。我想如果我遇到错误,它会错误地输出最后 2 个玩家,但它只是继续输出玩家 1。可以有人为我指明了正确的方向,说明为什么会这样吗?

这是我的链表class

public class PlayerLinkedList extends ShellLinkedList
{
public PlayerLinkedList()
{
  super();
}//end PlayerLinkedList constructor
public void insert(Player p)
{
  if(numberOfItems >= 3)
  {
     PlayerNode pn = new PlayerNode(p);
     head = pn;
     pn.setNext(head.getNext().getNext());
     numberOfItems++;
  }  
  else 
  {
     PlayerNode pn = new PlayerNode(p);
     if(head == null)
     {
        head = pn;
     }
     pn.setNext(head);
     head = pn;
     numberOfItems++;
  }     
}//end insert method
public Player delete(int searchID) throws DataStructureException
{
   PlayerNode current = head;
   PlayerNode previous = null;
   while(current != null && current.getPlayer().getID()!=searchID)
   {
     previous = current;
     current = current.getNext();
   }//end while
   if(current == null) //not found
     throw new DataStructureException(searchID + "not found: cannot be deleted");
     else
     {
     if(current == head)
        head = head.getNext(); //delete head
        else            
           previous.setNext(current.getNext());
           numberOfItems--;
           return current.getPlayer();        
     }//end else 
}//end delete
}//end class

我的ShellLinkedList也仅供参考class

public abstract class ShellLinkedList
{
   protected PlayerNode head;
   protected int numberOfItems;

   public ShellLinkedList()
   {
      head = null;
      numberOfItems = 0;
   }//end ShellLinkedList constructor

   public int getNumberOfItems()
   {
      return numberOfItems;
   }// end of getnumberOfItems

   public boolean isEmpty()
   {
      return (numberOfItems==0);
   }//end isEmpty

   public String toString()
   {
      String listString="";
      PlayerNode current = head;
      for(int i = 0; i<numberOfItems && current != null; i++)
      {
         listString += current.getPlayer().toString()+"\n";
         current = current.getNext();
      }
      return listString;
   }//end toString
}//end class

我的输入是:

Player one = new Player(1, "Mike", "Mario");
Player two = new Player(2, "Brian", "Halo");
Player three = new Player(3, "John", "Minecraft");
Player four = new Player(4, "Thrall", "WoW");
Player five = new Player(5, "Scott", "Metroid");
list.insert(one);
list.insert(two);
list.insert(three);
list.insert(four);
list.insert(five);
System.out.println(list.toString());

我的输出是:

id: 3   name: John  game: Minecraft
id: 2   name: Brian game: Halo
id: 1   name: Mike  game: Mario
id: 1   name: Mike  game: Mario
id: 1   name: Mike  game: Mario

您的代码存在一些问题,您的插入方法在 numberOfItems >= 3 时表现不同,这就是为什么您不能添加超过 3 次的原因。在该代码块中,您正在创建一个新的 PlayerNode 实例,但您没有保留对它的任何引用。

您还应该检查您是否期望正常的 List#add 行为附加到列表的末尾而不是开头。

我通过添加

解决了这个问题
head.getNext().setNext(pn);

之后
pn.setNext(head.getNext().getNext());