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.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null) return null;
ListNode slow=head;
ListNode fast=head;
while(fast!=null){
if(slow.val!=fast.val){
slow.next=fast;
slow=slow.next;
}
fast=fast.next;
}
slow.next=null;
return head;
}
}
本文介绍了一种算法,用于从已排序的链表中移除所有重复元素,确保每个元素只出现一次。提供了完整的Java代码实现,通过快慢指针技巧高效地解决了问题。
731

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



