有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何改进我的linkedlist练习?

我正在做《算法第四版》一书的练习1.3.26

/** * 1.3.26 Write a method remove() that takes a linked list
* and a string key as arguments and removes all of the nodes
* in the list that have key as its item field.
*
* java LinkListRemove to
* to to be or to to go to to to die
* ^z / ^d
* before remove:
* to to be or to to go to to to die
* result of remove:
* be or go die
* size: 4
*
*/

我的实现就在这里LinkListRemove,而且很有效。但我觉得它不优雅。是否可以只对单链表进行一次遍历

我的思路是一个两步过程:

  1. 从第一个删除连续键,处理后,链接列表以非键节点开始或为空
  2. 删除第一个节点后的匹配节点,现在链接列表以非关键节点开始或为空

如果要运行它,需要this jar file


共 (1) 个答案

  1. # 1 楼答案

    据我从你的问题中了解,你想从列表中删除与给定键匹配的所有元素

    是的,这可以在列表的一次迭代中完成。以下步骤应该会有所帮助:

    Node temp =null;
    if(key != null && first != null){
        if(key.equals(first.item)){               
            temp = first;
            first = first.next;
            temp.link=null;
            temp =null;
            return;
        }
        else{
            Node tempIt = first.link;
            temp = first;
            while(tempIt != null)
                {
                    if(key.equals(tempIt.item)){
                        temp.link = tempLt.link;
                        tempLt.link = null;
                        tempLt = null;
                    }
                    temp = tempLt;
                    tempLt= tempLt.next;
                }
            }
    }   
    return;