83. 删除排序链表中的重复元素(C++题解含VS可运行源程序)
1.题解
快慢指针
很简单
2.力扣C++源码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
//快慢指针 83.关键要保存要删除结点的pre 此题82不用,还简单点
if (head == NULL || head->next == NULL)return head;
//ListNode* pre = (ListNode*)malloc(sizeof(ListNode));
ListNode* slow = head;
ListNode* fast = head->next;
//pre->next = slow;
//ListNode* ans_head = pre;
while (slow != NULL && fast != NULL) {
if (slow->val == fast->val) {
int num = slow->val;
ListNode* p = fast;
//若重复,fast就后移,直到第一次出现当前fast与下一个元素不重复的情况
while ((fast->next != NULL) && (fast->val == fast->next->val)) {
fast = fast->next;
}
slow->next = fast->next;
slow = fast->next;