传送门 nowcoder leetcode
题目描述 在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表 1->2->3->3->4->4->5 处理后为 1->2->5 。
C++ 代码 - nowcoder 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 class Solution { public : ListNode* deleteDuplication (ListNode* pHead) { if (pHead == nullptr || pHead->next == nullptr ) return pHead; ListNode* dummy = new ListNode (-1 ); dummy->next = pHead; ListNode* prev = dummy; ListNode* cur = dummy->next; while (cur != nullptr ) { if (cur->next != nullptr && cur->val == cur->next->val) { while (cur->next != nullptr && cur->val == cur->next->val) { cur = cur->next; } prev->next = cur->next; cur = cur->next; } else { prev = prev->next; cur = cur->next; } } return dummy->next; } };
C++ 代码 - leetcode 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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 class Solution {public : ListNode* deleteDuplicates (ListNode* head) { if (head == nullptr ) return head; ListNode* dummy = new ListNode (-1 ); dummy->next = head; ListNode* cur = dummy; while (cur->next && cur->next->next) { if (cur->next->val == cur->next->next->val) { int t = cur->next->val; while (cur->next && cur->next->val == t) { cur->next = cur->next->next; } } else { cur = cur->next; } } return dummy->next; } };class Solution {public : ListNode* deleteDuplicates (ListNode* head) { if (head == nullptr ) return head; ListNode* cur = head; while (cur->next != nullptr ) { if (cur->val == cur->next->val) { cur->next = cur->next->next; } else { cur = cur->next; } } return head; } };class Solution {public : ListNode* deleteDuplicates (ListNode* head) { if (head == nullptr ) return head; ListNode* cur = head; for (ListNode* p = head->next; p; p = p->next) { if (cur->val != p->val) { cur->next = p; cur = cur->next; } } cur->next = nullptr ; return head; } };