原文:
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?
译文:
从一个未排序的链表中移除重复的项
进一步地,
如果不允许使用临时的缓存,你如何解决这个问题?
package chapter_2_LinkedLists;
import java.util.Scanner;
class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
}
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
class LinkList {
public Node head;
public Node tail;
public int size;
public boolean isEmpty() {
return size == 0;
}
public void add(int temp) {
Node node = new Node(temp);
size++;
if (head == null) {
head = node;
tail = node;
} else {
tail.next = node;
tail = node;
}
}
public void print() {
if (head == null) {
System.out.println("is empty");
} else {
Node p = head;
while (p != null) {
System.out.format("%3d", p.data);
p = p.next;
}
System.out.format("\n");
}
}
}
/**
从一个未排序的链表中移除重复的项
进一步地,
如果不允许使用临时的缓存,你如何解决这个问题?
*
*/
public class Question_2_1 {
/**
* 原地去除重复结点信息
* 遍历元素,每个元素出现判断之前是否出现过
*
* 时间复杂度 0(n2)
*/
public static void removeDulplicate(LinkList linkList) {
if (linkList.size < 2) {
return;
} else {
Node p, q;
p = linkList.head;
q = p.next;
while (q != null) {
Node tem = linkList.head;
while (tem != null && tem != q) {
if (tem.data == q.data) {
p.next = q.next;
q = q.next;
linkList.size--;
break;
} else {
tem = tem.next;
}
}
if (tem == q) {
p = q;
q = q.next;
}
}
}
}
/**
* 每次检查当前元素,判断之后是否出现重复,出现则去掉
*
* 时间复杂度 0(n2)
*/
public static void removeDulplicate2(LinkList linkList) {
if(linkList.size < 2) {
return;
} else {
Node cur, p, q;
cur = linkList.head;
while(cur != null) {
p = cur; q = cur.next;
while(q != null) {
if(q.data == cur.data) {
p.next = q.next;
q = q.next;
linkList.size --;
} else {
p = q;
q = q.next;
}
}
cur = cur.next;
}
}
}
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int testNum;
int len, temp;
testNum = scanner.nextInt();
scanner.nextLine();
while (testNum-- > 0) {
LinkList linkList = new LinkList();
len = scanner.nextInt();
scanner.nextLine();
for (int i = 0; i < len; i++) {
temp = scanner.nextInt();
linkList.add(temp);
}
scanner.nextLine();
linkList.print();
// removeDulplicate(linkList);
removeDulplicate2(linkList);
linkList.print();
}
}
}