Question:
Given two sorted linked list, and merge them without using extra space (using constant space is allowed). If there exist duplicated items, remove them and leave only one copy.
public static Node mergeSortedListWithouDuplicates(Node h1, Node h2) {
//one or both of the list(s) is (are) null
if(h1 == null) return h2;
if(h2 == null ) return h1;
Node newHead = (h1.data <= h2.data) ? h1 : h2;
Node small = null;
Node prev = newHead;
while (h1 != null && h2 != null) {
if (h1.data <= h2.data) {
small = h1;
h1 = h1.next;
} else {
small = h2;
h2 = h2.next;
}
if (prev.data != small.data) {
prev.next = small;
prev = small;
}
}
//deal with the remaining part of h1 or h2
while (h2 != null) {
if (prev.data != h2.data) {
prev.next = h2;
prev = h2;
}
h2 = h2.next;
}
while (h1 != null) {
if (prev.data != h1.data) {
prev.next = h1;
prev = h1;
}
h1 = h1.next;
}
// important
prev.next = null;
return newHead;
}
blog.csdn.net/beiyetengqing