如何在Java中完成将值添加到链表的方法?



所以我是Java链表的新手。我需要完成一个方法,将一个项目添加到链表。谁能帮我完成if语句,使方法正确工作?谢谢你的帮助。

void insert(int item)
  {
//find location to insert
Node current = head;
Node prev = null;
boolean located = false;
while(!located && current != null)//correct location found
{ 
  //I need to add a condition to the if statement below. What is the condition
    if(item
    current = current.link;//assign the next node from head to current node
  }
  //create new node and
  //refer to the correct location in list 
  Node newNode = new Node(item, current);
  //set link to refer to new node
  if (current == head)
  {
    head = newNode;//new node to head
  }
  else
  {
   //place new node after previous LINK reference not the node itself
   prev.link = newNode; 
  }    
}

我假设列表应该排序?如果没有,那么最简单的方法就是将新条目添加到列表的开头:

head = new Node(item, head);

但是,如果它需要排序,那么你需要找到第一个比你插入的项大的项:

while (!located && current != null) { 
    if (item < current.item) {
        prev = current;
        current = current.link;
    } else {
        located = true;
    }
}
Node newNode = new Node(item, current);
if (current == head) {
    head = newNode;
} else {
    prev.link = newNode; 
}    

这段代码寻找需要插入新项的点。此时,prevcurrent引用新节点前后的节点。如果到达列表末尾,则current为null。

相关内容

  • 没有找到相关文章

最新更新