题目
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->2->3
解法
思路
其实刚看到这道题,我直接想到的是[leetcode]26.Remove Duplicates from Sorted Array这道题的思路,所以设置了一个快指针和一个慢指针。
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null) return null;
ListNode fast = head;
ListNode slow = head;
while(fast != null) {
if(slow.val == fast.val)
fast = fast.next;
else{
slow.next = fast;
slow = slow.next;
}
}
slow.next = null;
return head;
}
}