样例
998 998 998 999 999 999 1000 1000 1000 删除后为998 999 1000
java代码
/**
* @Description:删除无序链表中值重复的链表
* @Author: lizhouwei
* @CreateDate: 2018/4/7 10:06
* @Modify by:
* @ModifyDate:
*/
public class Chapter2_13 {
public Node removeRep(Node head) {
Node pre = head;
Node cur = head.next;
//由于set 比较的是hashcode ,值相同的不同对象,hashcode不同,
//放Integer也不行,因为值大于100,则不在Integer类的缓存中放,所以也会是不同的值
// 所以不能放对象,而应该放它值的string类型。字符串是一个一个字符去比较的
Set<String> nodes = new HashSet<String>();
nodes.add(head.vlaue + "");
while (cur != null) {
//如果前面已经出现过,则让pre.next 指向当前节点的后继节点,
if (nodes.contains(cur.vlaue + "")) {
pre.next = cur.next;
} else {
pre = cur;
nodes.add(cur.vlaue + "");
}
cur = cur.next;
}
return head;
}
//测试
public static void main(String[] args) {
Chapter2_13 chapter = new Chapter2_13();
Link link = new Link();
//构有重复的造链表
for (int i = 1000; i > 997; i--) {
link.add(i);
link.add(i);
link.add(i);
}
Link.printLink(link.head);
Node head = chapter.removeRep(link.head);
Link.printLink(head);
}
}