LeetCode每日一题:remove duplicates f
2017-05-18 本文已影响6人
yoshino
问题描述
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given1->2->3->3->4->4->5, return1->2->5.
Given1->1->1->2->3, return2->3.
问题分析
对于这题,一旦发现有重复的节点,连同它本身也要删除,所以我们要新建一个辅助节点用来保存结点的前一个节点。
代码实现
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) return head;
ListNode preNode = new ListNode(0);
ListNode curNode = head;
preNode.next = head;
ListNode node = preNode;
while (curNode != null && curNode.next != null) {
if (curNode.val != curNode.next.val) {
node = curNode;
} else {
while (curNode.next != null && curNode.val == curNode.next.val) {
curNode = curNode.next;
node.next = curNode.next;
}
}
curNode = curNode.next;
}
return preNode.next;
}