移除未排序链表中的重复节点算法实现
2016-04-04 02:30
441 查看
分析:
想要移除重复节点,首先要知道哪些节点是重复的。我们这里使用散列表解决这个问题。
算法一
链表节点类
删除重复节点方法
算法二(不使用缓冲区)
如不借助额外的缓冲区,可以使用两个指针来迭代,current迭代访问整个链表,runner用于检查后续的节点是否重复。
算法的中心思想是双层遍历移除。
想要移除重复节点,首先要知道哪些节点是重复的。我们这里使用散列表解决这个问题。
算法一
链表节点类
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; } }
相关文章推荐
- JVM生产环境参数实例及分析[转]
- [IO]——输出目录等级
- [IO]——操作目录
- [IO]——创建文件
- [IO]——File对象
- [IO]——路径
- CentOS系统启动流程
- UVa 10391 - Compound Words
- 几个简单网络爬虫的例子--还没验证
- 进程强杀
- discuz 模拟批量上传附件发帖
- xcode中不小心删除了xcode里面的storyboard怎么办?
- gsl安装(Linux系统)
- firefox 扩展开发笔记(三):高级ui交互编程
- 内核数据结构总结
- Jquery Table 的基本操作
- spring mvc 文件上传并携带其他参数
- CSS变形transform(2d)
- 最长字串和
- springmvc