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
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
相关文章推荐
- merge two sorted linked list with duplicates
- merge two sorted linked list with duplicates
- LeetCode@LinkedList_21_Merge_Two_Sorted_Lists
- Merge Sorted Array leetcode java(回顾MergeTwoArray和MergeTwoLinkedList)
- 21. Merge Two Sorted Lists(Linked List-Easy)
- LeetCode 学习 LinkedList 专项(4)—— Merge Two Sorted Lists
- LeetCode 21 Merge Two Sorted Lists(合并两个已排序的链表)(Linked List)
- 【LeetCode】【Linked List】Merge Two Sorted Lists
- 21. Merge Two Sorted Lists(Linked List)
- LeetCode_Linked List_Merge Two Sorted Lists
- Remove Duplicates from Sorted List && Merge Two Sorted Lists && Linked List Cycle && Remove Nth Node
- LeetCode -- Merge Two Sorted Linked List
- LinkedList-21-Merge Two Sorted Lists
- let21 merge two linked list
- LeetCode: Merge two sorted linked lists
- LintCode - Merge Two Sorted List
- leetcode merge two sorted list
- leetcode Merge Two Linked List
- LeetCode: Merge Two Sorted Lists, Remove Duplicates/Element, strStr()
- 【Leetcode】Merge K Sorted Linked List