Home LeetCode - 203. Remove Linked List Elements
Post
Cancel

LeetCode - 203. Remove Linked List Elements

203. Remove Linked List Elements - easy

문제

Remove all elements from a linked list of integers that have value val.

제한사항

입출력 예

1
2
3
4
Example:

Input:  1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

풀이

  • Linked List
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        if(!head)
            return NULL;
        
        ListNode *node = new ListNode(0);
        node->next = head;
        head = node;
        
        while(node->next != NULL){            
            if(node->next->val == val)
                node->next = node->next->next; 
            else
                node = node->next;
        }
        
        return head->next;
    }
};
This post is licensed under CC BY 4.0 by the author.