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

时间:2015-04-12 21:13:43

标签: java linked-list

所以标题说我试图在链表的第三个位置输入一个节点。我最初尝试这样做的方法是在numberOfItems为> = 3之后在列表中插入两个位置。我想如果我收到一个错误,它将错误地输出最后两个玩家,但它只是继续输出播放器1.任何人都可以指出我为什么会发生这种情况的正确方向吗?

这是我的链表类

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类

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

2 个答案:

答案 0 :(得分:0)

您的代码存在一些问题,您的插入方法在numberOfItems >= 3时表现不同,这就是您无法添加超过3次的原因。在该代码块中,您正在创建一个新的PlayerNode实例,但您不会对其进行任何引用。

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

答案 1 :(得分:0)

我通过添加

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

之后

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