您的位置:首页 > 其它

CODE 50: Remove Duplicates from Sorted List II

2013-09-29 22:44 155 查看
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,

Given 
1->2->3->3->4->4->5
, return 
1->2->5
.

Given 
1->1->1->2->3
, return 
2->3
.

public ListNode deleteDuplicates(ListNode head) {
// Start typing your Java solution below
// DO NOT write main() function
if (null == head) {
return null;
}
ListNode node = new ListNode(0);
ListNode next = head.next;
int currentVal = head.val;
ListNode currentNode = node;
boolean isDouble = false;
while (null != next) {
if (next.val > currentVal) {
if (!isDouble) {
currentNode.next = new ListNode(currentVal);
currentNode = currentNode.next;
}
isDouble = false;
currentVal = next.val;
} else if (next.val == currentVal) {
isDouble = true;
}
next = next.next;
}
if (!isDouble) {
currentNode.next = new ListNode(currentVal);
}
return node.next;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: