问题描述
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given1->1->2, return1->2.
Given1->1->2->3->3, return1->2->3.
问题分析
删除链表中的重复节点,链表中很常见的操作,Java不需要考虑释放结点,而C++必须删除无用节点
代码实现
public ListNode deleteDuplicates(ListNode head) {
if (head == null) return null;
ListNode curNode = head;
while (curNode != null) {
while (curNode.next != null && curNode.val == curNode.next.val) {
curNode.next = curNode.next.next;
}
curNode = curNode.next;
}
return head;
}
网友评论