您的位置:首页 > 其它

merge two sorted linked list without duplicates

2012-06-01 09:29 399 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  duplicates merge list null