【发布时间】:2016-03-07 11:57:14
【问题描述】:
我正在通读 Cracking the coding interview by Gayle Mcdowell 这本书,并遇到了针对第 2 节链接列表中的一个问题的替代解决方案。特别是问题#2.1
删除重复项:编写代码以从未排序的链表中删除重复项。如果不允许使用临时缓冲区,您将如何解决此问题。
Example input = [1,2,2,6,4,4,2]
Example output = [1,2,6,4]
作者在书中给出的答案如下: 基本上,它保持“指针”,一个遍历链表,另一个检查所有后续节点是否有重复:
public void deleteDups(Node head) {
Node current = head;
while (current != null) {
Node runner = current;
while (runner.next != null) {
if (runner.next.data == current.data) {
runner.next = runner.next.next;
} else {
runner = runner.next;
}
}
current = current.next;
}
}
我使用了递归,我的代码看起来有点不同,尽管(我相信)做同样的事情:
public void removeRepetites(Node head) {
if (head == null) return;
int dataToRemove = head.data;
while (head.next != null) {
if (head.next.data == dataToRemove) {
head.next = head.next.next;
} else {
removeRepetites(head.next);
head = head.next;
}
}
}
你能发现我解决问题的方式有什么缺点吗?也许是更高的 O 空间/时间复杂度?
谢谢!
【问题讨论】:
标签: java data-structures linked-list