【leetcode】Remove Duplicates from Sorted List (easy)
3224 단어 LeetCode
For example,Given
1->1->2
, return 1->2
.Given 1->1->2->3->3
, return 1->2->3
. 아이디어:
간단한 문제라 할 말이 없다.
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if(head == NULL)
return NULL;
ListNode * ans = head;
ListNode * anscur = ans; //
ListNode * cur = head->next; //
while(cur != NULL)
{
if(anscur->val != cur->val) // ans
{
anscur->next = cur;
anscur = anscur->next;
}
cur = cur->next;
}
anscur->next = NULL; // , ans
return ans;
}
};
대신의 코드는 더욱 간결하다. 새로운 두결점을 만들 필요가 없다. 원래의 두결점을 사용하면 된다.
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if(NULL == head) return head;
ListNode *cur = head, *nxt = head->next;
while (nxt) {
if (cur->val != nxt->val)
cur = cur->next = nxt;
else if (!nxt->next)
cur->next = nxt->next;
nxt = nxt->next;
}
return head;
}
};