83. Remove Duplicates from Sorted List
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2 Output: 1->2
Example 2:
Input: 1->1->2->3->3 Output: 1->2->3
my code:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* deleteDuplicates(ListNode* head) { ListNode* dummy = new ListNode(0); dummy->next = head; ListNode* p = dummy; while (p->next != NULL && p->next->next != NULL) { int sameNum = p->next->val; p = p->next; while (p->next!= NULL && p->next->val == sameNum) { if (p->next->next != NULL) p->next = p->next->next; else p->next = NULL; } } return dummy->next; } };
Runtime: 12 ms, faster than 36.37% of C++ online submissions for Remove Duplicates from Sorted List.
永远渴望,大智若愚(stay hungry, stay foolish)