82. 删除排序链表中的重复元素 II(C++题解含VS可运行源程序)
1.题解
快慢指针
2.力扣C++源码
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
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;
while ((fast->next != NULL) && (fast->val == fast->next->val)){
fast = fast->next;
}
slow = fast->next;
pre->next = slow;
if (slow != NULL) fast = slow->next;
}
else {
pre->next = slow;
pre = pre->next;
slow = slow->next;
fast = fast->next;
}
}
return ans_head->next;
}
};
3.VS可运行源程序
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<limits>
#include<algorithm>
#include<math.h>
#pragma warning(disable:4996)
using namespace std;
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) {
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;
while ((fast->next != NULL) && (fast->val == fast->next->val)){
fast = fast->next;
}
slow = fast->next;
pre->next = slow;
if (slow != NULL) fast = slow->next;
}
else {
pre->next = slow;
pre = pre->next;
slow = slow->next;
fast = fast->next;
}
}
return ans_head->next;
}
};
void List_TailInsert2(ListNode** head)
{
*head = (ListNode*)malloc(sizeof(ListNode));
ListNode* rear = *head;
ListNode* p;
int num;
scanf("%d", &num);
while (num != 9999) {
p = (ListNode*)malloc(sizeof(ListNode));
p->val = num;
rear->next = p;
rear = p;
scanf("%d", &num);
}
rear->next = NULL;
}
int main()
{
printf("输入链表数据(以9999结束):");
ListNode* head;
List_TailInsert2(&head);
Solution test;
head = test.deleteDuplicates(head->next);
printf("删除排序链表中的重复元素后的链表数据为:");
while (head) {
printf("%d ", head->val);
head = head->next;
}
printf("\n");
system("pause");
return 0;
}