본문 바로가기
Data Structure & Algorithms/Linked lists

[Linked lists][leetcode] Remove Duplicates from Sorted List

by 담백로봇 2023. 1. 10.

링크드 리스트.... 너무 헷갈린다. 여기서부터 진짜인가!!

 

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:

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

Example 2:

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

 

Constraints:

  • The number of nodes in the list is in the range [0, 300].
  • -100 <= Node.val <= 100
  • The list is guaranteed to be sorted in ascending order.

분석: 

/**
 * Definition for singly-linked list.
 //  아 이제좀 이해가 되네. struct 로 ListNode라는 구조체를 만들고 이 안에 val담을것과 어떤 
 //  NodeList를 가르키는 next를 집어넣은것이구나!. 그림이 그려진다. 
 
 * struct ListNode { // single-linked list structure이다 
 *     int val; // 2개의 member functions 선언 
 *     ListNode *next; // 다른 ListNode type을 가르킬수있는 포인터 !!!!!
 *     ListNode() : val(0), next(nullptr) {} //3개의 contstructors가 선언되었다. default constructor로 val:0 ,next 는 nullptr 이니셜라이징 됨
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
 
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) { // 위에 주어진 동작을 실행하는 member function으로 linked list를 집어넣으면 결과값 반환되도록 
    
        ListNode *current = head;// 입력된 linked node를 가르키도록, 이렇게되면 
        // head만 입력이되면 이 뒤에 딸려있는 노드들을 줄줄이 소환할 수 있다!
        
        while( current != NULL && current -> next != NULL){
            
            if(current->next->val == current->val){
                current->next = current->next->next;
            }else{
                current=current->next; // current node가 한단계씩 다음 노드로 이동되어 next값이 null이 되는 순간 리턴
            }
        }
        return head;   
    }
};

댓글