-
Notifications
You must be signed in to change notification settings - Fork 0
/
3_2.java
138 lines (104 loc) · 2.57 KB
/
3_2.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import java.util.HashSet;
import java.util.Scanner;
public class RemoveDuplicate {
//2.1 Write code to remove duplicates from an unsorted linked list.
//Todo: String should be replaced by generic class
public static class Node {
private Node next;
private char data;
public Node(){
next = null;
data = 0;
}
public Node(char ch){
next = null;
data = ch;
}
public char getData(){
return data;
}
private void setData(char ch){
data = ch;
}
public Node getNext(){
Node node = next;
return node;
}
public void setNext(Node node){
next = node;
}
}
//convert string into single unsorted linked list
public static Node init(char[] content, int length){
Node head = new Node();
Node temp = head;
for(int i=0; i<length; i++){
temp.setData(content[i]);
System.out.println(content[i]);
Node node = new Node();
temp.setNext(node);
temp = temp.getNext();
}
return head;
}
//print out the single linked list
public static void printList(Node head){
while(head.getNext() != null){
System.out.println(head.getData());
}
}
//method1: with buffer
public static Node removeDuplicate1(Node head){
HashSet<Character> set = new HashSet<Character>();
Node previous = head;
Node current = head.getNext();
set.add(previous.getData());
if(!set.contains(current.getData())){
set.add(current.getData());
previous = previous.getNext();
current = current.getNext();
}
else{
previous.setNext(current.getNext());
}
return head;
}
//method2: without buffer
public static Node removeDuplicate2(Node head){
Node previous = head;
Node current = head.getNext();
Node runner = current.getNext();
boolean isDuplicate = false;
while(head.getNext() != null){
while(current.getData() != runner.getData() && runner.getNext() != null){
runner = runner.getNext();
isDuplicate = true;
}
if(isDuplicate){
previous.setNext(current.getNext());
isDuplicate = false;
}
previous = previous.getNext();
current = current.getNext();
}
return head;
}
//public static
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Please enter your string:");
String in = input.nextLine();
int length = in.length();
char[] content = in.toCharArray();
Node head = init(content, length);
Node newHead1 = removeDuplicate1(head);
Node newHead2 = removeDuplicate2(head);
printList(newHead1);
printList(newHead2);
input.close();
}
}