Topic: Write code to remove duplicates from an unsorted linked list. FOLLOW UP How would you solve this problem if a temporary buffer is not allowed?
//知识点1:为什么父类需要一个空的无参构造器?
Class SuperClass{//父类没有默认构造器,但是有含参构造器
Public SuperClass(String param){}}
Class ChildClass{}
如果没有给父类一个默认的构造器,上述子类不能通过编译。编译器会给子类提供默认的构造器,不会给父类提供,因为已经定义了一个。子类实例化时,会调用父类的默认构造器,但父类没有,所以错误。解决的办法是给父类一个空无参构造器,以免子类编译出错。
//知识点2:Interger.valueOf(int i): return an Interger instance representing int’s value
Interger.valueOf(String s):return an Integer object holding the value of the String
//方法1:建一个Hashtable即可,Space: O(N)
//方法2:每一个跟后面所有的比较一遍即可。Iterate with two pointers, one iterates through the linked list, other checks all subsequent nodes. Space: O(1), Time: O(N2).【Follow up: (no buffer allowed)】
import java.util.Hashtable;
public class List {
int data;
List next;
public List(int d) {
this.data = d;
this.next = null;
}
void appendToTail(int d) {//依次在最后一个节点的后面追加元素
List end = new List(d);
List n = this;
while (n.next != null) {//判断是否是最后一个节点,如果不是,往后移
n = n.next;
}
n.next = end;//把这个节点设为最后一个节点
}
void print() {
List n = this;
System.out.print("{");
while (n != null) {
if (n.next != null)
System.out.print(n.data + ", ");
else
System.out.println(n.data + "}");
n = n.next;
}
}
void removeDuplicate() {
Hashtable<Integer, Boolean> table = new Hashtable<Integer, Boolean>();
List n = this;// this始终是链表的第一个元素。必须如此,如果是双向链表,previous=null
table.put(Integer.valueOf(n.data), true);
while (n.next != null) {
if (table.containsKey(Integer.valueOf(n.next.data))) {
n.next = n.next.next;
} else {
table.put(Integer.valueOf(n.next.data), true);
n = n.next;
}
}
}
void removeDuplicate1() {
List n = this;
List m;
while (n != null) {
m = n;
while (m.next != null) {
if(m.next.data == n.data)
m.next = m.next.next;
else
m = m.next;
}
n = n.next;
}
}
public static void main(String args[]) {
List list = new List(0);
list.appendToTail(1);
list.appendToTail(2);
list.appendToTail(2);
list.appendToTail(3);
list.appendToTail(3);
list.appendToTail(4);
list.appendToTail(1);
list.appendToTail(2);
list.appendToTail(0);
list.print();
//list.removeDuplicate();
list.removeDuplicate();
list.print();
}
}
// 结果
{0, 1, 2, 2, 3, 3, 4, 1, 2, 0}
{0, 1, 2, 3, 4}