【IT笔试面试题整理】删除无序链表中重复的节点
来源:互联网 发布:python视频教程在线 编辑:程序博客网 时间:2024/05/14 10:32
【试题描述】定义一个函数,输入一个链表,删除无序链表中重复的节点
【参考代码】
方法一:
Without a buffer, we can iterate with two pointers: “current” does a normal iteration, while
“runner” iterates through all prior nodes to check for dups Runner will only see one dup
per node, because if there were multiple duplicates they would have been removed already
1 public static void deleteDups(LinkList head) 2 { 3 if (head == null) 4 return; 5 Link previous = head.first; 6 Link current = previous.next; 7 while (current != null) 8 { 9 Link runner = head.first;10 while (runner != current)11 {12 if (runner.id == current.id)13 {14 Link tmp = current.next;15 previous.next = tmp;16 current = tmp;17 break;18 }19 runner = runner.next;20 }21 22 if (runner == current)23 {24 previous = current;25 current = current.next;26 }27 }28 29 System.out.println("-----------");30 head.displayList();31 }
方法二:
If we can use a buffer, we can keep track of elements in a hashtable and remove any dups:
public static void deleteDups2(LinkList head) { if (head == null) return; Hashtable table = new Hashtable(); Link previous = null; Link current = head.first; while (current != null) { if (table.containsKey(current.id)) previous.next = current.next; else { table.put(current.id, true); previous = current; } current = current.next; } System.out.println("-----------"); head.displayList(); }
阅读全文
0 0
- 【IT笔试面试题整理】删除无序链表中重复的节点
- 《剑指Offer》面试题57:删除链表中重复的节点
- 【剑指offer】面试题18:删除链表中重复的节点
- 【IT笔试面试题整理】寻找二叉树两节点的最近的公共祖先
- 笔试题:删除链表中重复的节点
- 【IT笔试面试题整理】二叉查找树后继节点和前驱节点查找 --转
- 【IT笔试面试题整理】二叉树中和为某一值的路径--从根到叶子节点
- 【IT笔试面试题整理】字符串的排列
- 【IT笔试面试题整理】字符串的组合
- 【IT笔试面试题整理】丑数
- 【IT笔试面试题整理】位操作
- 【IT笔试面试题整理】链表
- 【IT笔试面试题整理】 二叉树任意两个节点间最大距离
- 剑指offer面试题18:删除链表中重复的节点-java
- 整理的笔试面试题
- 整理的笔试面试题
- 删除无序链表中值重复出现的节点
- 【IT笔试面试题整理】笔试和面试中常见的智力题
- 【IT笔试面试题整理】反转链表
- 【IT笔试面试题整理】字符串转数组+数组转字符串
- 【IT笔试面试题整理】判断链表是否存在环路,并找出回路起点
- 【IT笔试面试题整理】判断一个二叉树是否是平衡的?
- 关于笔记本安装Deepin 或者ubuntu操作系统,无法进入界面。
- 【IT笔试面试题整理】删除无序链表中重复的节点
- 如何配置MySQL数据库超时设置
- 【IT笔试面试题整理】判断一个树是否是另一个的子树
- 【IT笔试面试题整理】有序数组生成最小高度二叉树
- 【IT笔试面试题整理】给定二叉树,给每层生成一个链表
- XSS漏洞手工检测
- 【IT笔试面试题整理】位操作
- maven------junit作用
- 【IT笔试面试题整理】链表