Remove Duplicates from Sorted List
Description
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example Given 1->1->2, return 1->2. Given 1->1->2->3->3, return 1->2->3.
Link
Method
- x
- x
Example
- 1
/** * Definition of ListNode * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */ class Solution { public: /** * @param head: The first node of linked list. * @return: head node */ ListNode *deleteDuplicates(ListNode *head) { // write your code here if (!head) { return nullptr; } ListNode dummy(INT_MIN); ListNode* result = &dummy; ListNode* cur = result; cur->next = head; cur = cur->next; head = head->next; while (head) { if (cur->val != head->val) { cur->next = head; cur = cur->next; } head = head->next; } cur->next = nullptr; return result->next; } };
Similar problems
x
Tags
x