Java -不考虑链表中的最终元素



下面方法的对象是删除链表中第一个数字之后大于前一个数字的任何数字。一旦它被删除,它还会检查这个数字与前一个数字-否则继续。

示例列表:

[1,2,3,4,5,0,0,1,2,1]

将产生

[1,0,0]

因为(2> 1)2移除,(3> 1)3移除,(4> 1)4移除,(5> 1)5移除),(0 <1)没有发生任何事情(当前list =[1,0],(0 == 0),没有发生任何事情list =[1,0,0],(1> 0)被删除…等

我现在的代码把最后一个元素留在了末尾所以它不是[1,0,0]而是[1,0,0,1]

当前代码:

public void deleteLarger() {
    Node<T> current = head; 
    Node<T> previous = null;
    while(current != null) {
        if (previous != null){
            if (current.getValue().compareTo(previous.getValue()) > 0){
                remove(current.getValue());
            }
            if (current.getValue().compareTo(previous.getValue()) < 0){
                remove(previous.getValue());
            }
        }
        previous = current;
        current  = current.getNext(); 
    }
}

谢谢!

public void deleteLarger() {
    Node<T> current = head; 
    Node<T> previous = null;
    while(current != null) {
        if (previous != null && current.getValue().compareTo(previous.getValue()) > 0){
            Node<T> toremove = current;
            current = current.getNext(); 
            remove(toremove.getValue());  // or remove(toremove); ?
        } else {
            previous = current;
            current  = current.getNext(); 
        }
    }
}

相关内容

  • 没有找到相关文章

最新更新