给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
#include <iostream>
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) {}
};
/// LinkedList 测试辅助函数
// 根据n个元素的数组arr创建一个链表, 并返回链表的头
ListNode* createLinkedList(int arr[], int n){
if(n == 0)
return NULL;
ListNode* head = new ListNode(arr[0]);
ListNode* curNode = head;
for(int i = 1 ; i < n ; i ++){
curNode->next = new ListNode(arr[i]);
curNode = curNode->next;
}
return head;
}
// 打印以head为头结点的链表信息内容
void printLinkedList(ListNode* head){
ListNode* curNode = head;
while(curNode != NULL){
cout << curNode->val << " -> ";
curNode = curNode->next;
}
cout << "NULL" << endl;
return;
}
// 释放以head为头结点的链表空间
void deleteLinkedList(ListNode* head){
ListNode* curNode = head;
while(curNode != NULL){
ListNode* delNode = curNode;
curNode = curNode->next;
delete delNode;
}
return;
}
class Solution {
public:
ListNode* deleteDuplicates(ListNode *head) {
if (head == NULL)
return head;
ListNode* cur = head;
while (cur->next != NULL){
if (cur->val == cur->next->val){
cur->next = cur->next->next;
}else {
cur = cur->next;
}
}
return head;
}
};
int main (){
int arr[] = {1, 1, 2, 3, 3};
int n = sizeof(arr)/sizeof(int);
ListNode* head = createLinkedList(arr, n);
printLinkedList(head);
ListNode* head2 = Solution().deleteDuplicates(head);
printLinkedList(head2);
deleteLinkedList(head2);
return 0;
}