Problem Solving/LeetCode

[LeetCode] 83. Remove Duplicates from Sorted List

kimdozzi 2023. 3. 10. 14:59

출처 : https://leetcode.com/problems/remove-duplicates-from-sorted-list/

 

Remove Duplicates from Sorted List - LeetCode

Can you solve this real interview question? Remove Duplicates from Sorted List - Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.   Example 1: [https://assets.le

leetcode.com

 

 

 

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