320x100
https://leetcode.com/problems/remove-duplicates-from-sorted-list/
Node의 목록이 주어졌을 때 중복값을 제거한 리스트를 반환하는 문제다.
[C++]
/**
* 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* deleteDuplicates(ListNode* head) {
ListNode* prev = nullptr;
ListNode* node = head;
while (node)
{
if (prev && node->val == prev->val)
{
prev->next = node->next;
}
else
{
prev = node;
}
node = node->next;
}
return head;
}
};
[Python3]
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
node = head
while node:
if node.next and node.val == node.next.val:
node.next = node.next.next
else:
node = node.next
return head
320x100
'코딩테스트 준비 > leetcode' 카테고리의 다른 글
78. Subsets (0) | 2021.08.18 |
---|---|
141. Linked List Cycle (0) | 2021.08.17 |
88. Merge Sorted Array (0) | 2021.08.10 |
14. Longest Common Prefix (0) | 2021.08.09 |
118. Pascal's Triangle (0) | 2021.08.08 |