欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

[leetcode]83.Remove Duplicates from Sorted List

程序员文章站 2024-03-22 14:56:46
...

题目

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;
    }
}