复制单链接列表 [英] duplicate the singly linked list

查看:149
本文介绍了复制单链接列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[3,5,4,2,1]我需要删除靠近尾部的节点,这应该是[1,2,3,5,4]任何建议?

[3, 5, 4, 2, 1] where I need the delete the nodes close to the tail which is it should be like [1, 2, 3, 5, 4] any suggestions?

public void delete() {
    for(Node<T> current = getHead(); current != null; current = current.getNext()){

                System.out.println(temp.getValue());
                removeValue(temp.getValue());
            }
        }
    }
}


推荐答案

你不需要删除任何东西(我的意思是不是通过调用 removeValue )。只需将您遇到的值存储在集合中,并且如果该值已经在集合中,则会重新链接您的列表。如果您没有使用库代码的权利,请使用二叉搜索树实现您的设置,这将非常简单而且非常有效。

You don't need to remove anything at all (I mean not by calling removeValue). Just store the values you encounter in a set and if the value is already in the set, re-link your list in consequence. If you don't have the right to use library code, implement your set with a binary search tree, it will be easy and quite efficient.

这是我将如何做,假设我执行 Set

This is how I would do, assuming I have an implementation of Set :

public void makeUnique() {
    Set<T>  set      = new MySet<>();
    Node<T> current  = getHead();
    Node<T> previous = null;
    while (current != null) {
        // if current.getValue() is already in the set, we skip this node
        // (the add method of a set returns true iff the element was not 
        // already in the set and if not, adds it to the set)
        if (set.add(current.getValue()) { 
            // previous represents the last node that was actually inserted in the set.
            // All duplicate values encountered since then have been ignored so 
            // previous.setNext(current) re-links the list, removing those duplicates
            if (previous != null) {
                previous.setNext(current); 
                current.setPrevious(previous);
             }
            previous = current;
        }
        current = current.getNext();
    }
}

这篇关于复制单链接列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆