题目
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
代码
public static ListNode deleteDuplicates(ListNode head) {
if (head==null || head.next==null) return head;
ListNode first = head;
ListNode second=head.next;
while(second!=null){
if(first.val==second.val){
second=second.next;
first.next=second;
}
else{
first=first.next;
second=first.next;
}
}
return head;
}
/********************************
* 本文来自博客 “李博Garvin“
* 转载请标明出处:http://blog.csdn.net/buptgshengod
******************************************/

本文提供了一种解决方案,用于从已排序的链表中移除所有重复元素,确保每个元素只出现一次。通过一个示例性的Java方法实现,该方法遍历链表并比较相邻节点值,如果发现重复则跳过重复节点。

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



