【问题标题】:move item to the front of the LinkedList将项目移动到 LinkedList 的前面
【发布时间】:2015-05-09 04:07:18
【问题描述】:

我的方法是首先在列表中找到某个元素,如果为真,则将包含该值的节点移动到列表的前面,而不创建或删除新节点。这是我到目前为止所拥有的,我不认为移动节点部分正在工作,感谢任何帮助!

public boolean findMove(E e){
    Node previous=null;
    Node current=head;
    while(current !=null){
        if(e.equals(current.item)){
            previous.next=current.next;
            current.next=head;
            head=current;
            System.out.println("True");
            return true;
        }
        current=current.next;
    }
    System.out.println("False");
    return false;
}

【问题讨论】:

  • 您没有在循环中更新previous
  • @John 请试试我的回答是否适合你?
  • boolean return 是绝对必要的还是你可以抛出一个NoSuchElementException?这方面会阻碍您以非常简洁的方式执行此操作。

标签: java linked-list nodes


【解决方案1】:

你能试试这个吗?看来你没有更新previous

public boolean findMove(E e){
    Node previous=head;
    Node current=head;
    while(current !=null){
        if(e.equals(current.item)){
            //Found the item
            previous.next=current.next;
            current.next=head;
            head=current;
            System.out.println("True");
            return true;
        }
        previous = current;
        current=current.next;
    }
    System.out.println("False");
    return false;
}

【讨论】:

  • 您可能还需要验证代码的边界条件。它可能需要在这里和那里进行一些小的更改。很高兴帮助你:)
【解决方案2】:

您的代码存在一些问题:

  • 在循环中,对 head 的引用没有存储在任何地方。假设 head 是起点,你不应该改变它。但在循环内部,由于“current”被更新为指向下一个节点,head 不再是 LinkedList 的有效起点。
  • 如果您在第一个位置(头节点)找到该项目,则不应移动它(检查上一个 = null)。

上面的东西试试这个:

public boolean findMove(E e){
    Node previous=null;
    Node current=head;
    Node headerNode = head;
    while(current !=null){
        if(e.equals(current.item) && previous != null){
            // Update the previous node to point to the next node
            previous.next=current.next;
            // Move the current node to point to the starting position
            current.next=headerNode;
            // Mark the current node as header node
            headerNode=current;

            System.out.println("True");
            return true;
        }
        // Not found - Update Previous to point the current node
        previous = current;
        current=current.next;
    }
    System.out.println("False");
    return false;
}

【讨论】:

  • 为什么需要previous != null条件?请解释一下。
  • 如果被搜索的元素是头节点本身,那么previous仍然是null。访问previous.next会抛出空指针异常。
  • currentprevious 都只指向head 怎么样?
  • 应该也可以。因为这只是 LinkedList 开头的故障。但是头节点仍然没有保留在循环内。所以,我们需要另一个方法级变量Node headerNode = head; ,这样我们就可以跳回头部节点。
猜你喜欢
  • 1970-01-01
  • 2014-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-16
  • 2019-10-05
相关资源
最近更新 更多