N

(Leet Code c++)Remove Linked List Elements 본문

Leet Code 알고리즘

(Leet Code c++)Remove Linked List Elements

naeunchan 2021. 7. 22. 11:23
728x90
반응형

203. Remove Linked List Elements

 

Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

 

Example 1:

Input: head = [1,2,6,3,4,5,6], val = 6 Output: [1,2,3,4,5]

Example 2:

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

Example 3:

Input: head = [7,7,7,7], val = 7 Output: []

 

Constraints:

  • The number of nodes in the list is in the range [0, 104].
  • 1 <= Node.val <= 50
  • 0 <= val <= 50

Linked List에서 원소를 제거한 후 결과를 리턴.

 

우선 처음에는 head(current)가 NULL인지 확인한다.

NULL인 경우는 바로 NULL값을 리턴하여 종료.

 

NULL이 아닌 경우 current->next가 NULL이 아닐 때까지 반복.

current->next를 간편하게 next로 저장한다.

 

next->val과 지우려고 하는 val이 같은지 확인하여, 같은 경우 current->next = next->next로 바꿔 준다.

같지 않다면 current = next로 하여 다음 링크로 이동.

 

이를 반복하면 연결 리스트에서 val을 모두 지울 수 있다.

단, 마지막에 head 값이 val인지 확인하고

head->val == val 이라면 head->next를 리턴.

아니라면 head를 리턴!

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode * current = head;
        
        if(current == NULL){
            return NULL;
        }
        
        while(current->next != NULL){
            ListNode * next = current->next;
            
            if(next->val == val){
                current->next = next->next;
            }
            else{
                current = next;
            }
        }
        
        if(head->val == val){
            return head->next;
        }
        
        return head;
    }
};
728x90
반응형

'Leet Code 알고리즘' 카테고리의 다른 글

(Leet Code c++)Count Primes  (0) 2021.07.22
(Leet Code c++)Happy Number  (0) 2021.07.22
(Leet Code c++)Number of 1 Bits  (0) 2021.07.21
(Leet Code c++)Reverse Bits  (0) 2021.07.21
(Leet Code c++)Factorial Trailing Zeroes  (0) 2021.07.21