您的位置:首页 > 其它

移除未排序链表中的重复节点算法实现

2016-04-04 02:30 441 查看
分析:

想要移除重复节点,首先要知道哪些节点是重复的。我们这里使用散列表解决这个问题。

算法一

链表节点类

public class LinkedListNode {

LinkedListNode next = null;//指向的下一个链表

public int data;

}


删除重复节点方法

public static void deleteDups(LinkedListNode n){
Hashtable<Object,Object> table = new Hashtable<Object,Object>();
LinkedListNode previous = null;
while(n!=null){
if(table.containsKey(n.data)){
previous.next = n.next;
}else{
table.put(n.data,true);
previous = n;
}
n = n.next;
}
}


算法二(不使用缓冲区)

如不借助额外的缓冲区,可以使用两个指针来迭代,current迭代访问整个链表,runner用于检查后续的节点是否重复。

算法的中心思想是双层遍历移除。

public static void deleteDups2(LinkedListNode head){
if(head==null){
return;
}
LinkedListNode current = head;
while(current!=null){
/*移除后续值相同的所有节点*/
LinkedListNode runner = current;
while(runner.next!=null){
if(runner.next.data == current.data){
runner.next = runner.next.next;
}else{
runner = runner.next;
}
}
current = current.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: