LeetCode - 83. Remove Duplicates from Sorted List(Linked List)*

YAMAMAMO·2023년 1월 3일
0

LeetCode

목록 보기
96/100

문제

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.

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

Example 1:

Input: head = [1,1,2]
Output: [1,2]

Example 2:

Input: head = [1,1,2,3,3]
Output: [1,2,3]

풀이

class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head==null||head.next==null) return head;
        ListNode newHead = head;
 
        while(newHead.next!=null){
            if(newHead.val==newHead.next.val){
                newHead.next=newHead.next.next;
            }else{
                newHead = newHead.next;
            }
        }
        return head;
    }
}
profile
안드로이드 개발자

0개의 댓글