删除其余部分后删除链表中的第一个节点

时间:2013-07-01 17:12:19

标签: algorithm singly-linked-list

我必须以包的形式实现链表。通常,袋子没有移除,但在这种情况下我需要一个。

当我运行我的测试客户端并调用remove时,除了第一个值之外,我的链表中该项的所有实例都将被删除。

基本上我的输出看起来像这样:

removed all 9s: 4 4 4 4 4 3 3 3 3 3 2 2 2 2 2 1 1 1 1 1 4 4 3 3 2 2 1 1 
removed all 3s: 4 4 4 4 4 2 2 2 2 2 1 1 1 1 1 4 4 2 2 1 1 
removed all 1s: 4 4 4 4 4 2 2 2 2 2 4 4 2 2
removed all 4s: 4 2 2 2 2 2 2 2 
removed all 2s: 4 

这是我的代码:

public void remove (int item)
{
  // TODO
  Node previous = null; 
  Node current = first;

  if (first == null) // list is empty do nothing
  {
  }
  else if (first.item == item) // item occurs in first node 
  {
    //previous = first;
    first = first.next;
  } // skip around first node
  else
  {
    // find the node before item                                            
    for (Node p = first.next, q = first; p != null; q = p, p = q.next)
    {
      if (p.item == item)
      {
        q.next = p.next;
        //p.next = q.next;
        //return;            
      }
    }
  }

  while (current != null)
  {
    if(current.item == item)
    {
      current = current.next;            
      if (previous == null)
        previous = current;
      else
        previous.next = current;
    }
    else
    {
      previous = current;
      current = current.next;
    }
  } //end while
  //return;
}

以下是测试客户端代码:

b1.remove(9);
print ("removed all 9s", b1); // does nothing
b1.remove(3);

print ("removed all 3s", b1);
b1.remove(1);

print ("removed all 1s", b1);
b1.remove(4);

print ("removed all 4s", b1);
b1.remove(2);

print ("removed all 2s", b1); // should be empty

有人可以帮我弄清楚为什么4应该被删除之后仍然存在?

1 个答案:

答案 0 :(得分:0)

问题在于

if (previous == null){previous = current;}

前三项是4.
在删除(4)时,遵循的步骤是
first = first.next //首先指向第2项目4,但当前仍然指向第一项目4 if(current.item == item) current = current.next //现在当前也指向第二个4.
previous = current //由于previous是null,所以if语句为true,previous也指向second 4.

在furthur while循环中,previous不为null,并且您将当前分配给previous.next。所以你永远不会跳过第二个。

<强>更新: 假设您有一个节点head指向其他节点后面的虚拟节点。

remove(item)
{
    previous = head;
    current = head.next;
    while(current!=null)
    {
        if(current.item == item)
        {
            previous.next = current.next;
            current = current.next;
        }
        else
        {
            previous = current;
            current = current.next;
        }
    }
}