LeetCode-Remove Duplicates from Sorted List

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/82963259

Description:
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

题意:将给定的已排序链表中重复的元素去除,返回新的链表;

解法:因为此时的链表是已经排序好的了,我们只需要判断当前元素是否和前一个元素是相同的,就可以找出重复的元素;

Java
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode next = head;
        while (next != null) {
            if (next.next != null && next.next.val == next.val) {
                next.next = next.next.next;
            } else {
                next = next.next;
            }
        }
        return head;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/82963259