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.youkuaiyun.com/beiyetengqing
本文介绍了一种算法,在不使用额外空间的情况下,将两个已排序的链表合并,并移除重复元素。
1801

被折叠的 条评论
为什么被折叠?



