83. 删除排序链表中的重复元素
/** * 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 *current; current = head; if(current==NULL||current->next==NULL) return head; while(current) { while(current->next&¤t->next->val == current->val)// 将重复节点全部删除完再移动到下一个元素 current->next = current->next->next; current = current->next; } return head; } };
82. 删除排序链表中的重复元素 II
/** * 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 *pre, *current,*head_res; current = head; if(current==NULL||current->next==NULL) return current; head_res = new ListNode; head_res->next = head; pre = head_res; int del_val; while(current&¤t->next) { if(current->val == current->next->val) { del_val = current->val;//del_val = 3 del_val = 4 while(current&¤t->val==del_val) { pre->next = current->next; //2->3 2->4 2->5 current = current->next; //current = 3 current = 4 current = 5 } } else { pre->next = current;//0->1 1->2 current = current->next;//current = 2 current = 3 pre = pre->next;//pre = 1 pre = 2 } } return head_res->next; delete(head_res); } };
原文:https://www.cnblogs.com/jessica216/p/13382173.html