LinkedList - 83. Remove Duplicates from Sorted List

时间:2022-07-25
本文章向大家介绍LinkedList - 83. Remove Duplicates from Sorted List,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

83. Remove Duplicates from Sorted List

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

思路:

这一题和26题移除数组中重复的元素一样都是去重,只不过这里的数据是链表,思路就是判断当前节点数值和下一个的节点值是否相同,如果相同就跳过下一个节点。不同就移动指针到下一个节点继续判断。

代码:

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) {
        if (head == null || head.next == null) return head;
        
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        ListNode explore = dummy.next;
        while (explore != null && explore.next != null) {
            if (explore.next.val == explore.val) explore.next = explore.next.next;
            else explore = explore.next;
        }
        
        return dummy.next;
    }
}