题目:
今天的题目因为要保留一个,所以可以比昨天的题目少使用一个指针。
今天使用delete删除元素没有报错,看来是第一次真正处理好了内存;
C++代码附带测试:
#include<iostream>
#include<cstring>
using namespace std;
struct ListNode{
int data;
ListNode* next;
ListNode(int n):data(n),next(nullptr){}
};
class List{
public:
List(){
head = new ListNode(0);
ListNode* ptr = head;
int arr[] = {1,1,2,2};
int n = sizeof(arr)/sizeof(int);
for(int i=0;i<n;i++){
ListNode *p = new ListNode(arr[i]);
ptr->next = p;
ptr = ptr->next;
}
}
ListNode* getHead(){return head;}
friend ostream& operator<<(ostream& os,List& list){
ListNode* ptr = list.getHead();
ptr = ptr->next;
while(ptr!=nullptr){
os<<ptr->data<<" ";
ptr = ptr->next;
}
return os;
}
private:
ListNode *head;
};
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode* suphead = new ListNode(0);
suphead->next = head;
if(head==nullptr){
return head;
}
if(head->next == nullptr){
return head;
}
ListNode* pre = head;
ListNode* cur = head->next;
while(cur!=nullptr){
if(pre->data!=cur->data){
pre = cur;
cur = cur->next;
}else{
while(cur!=nullptr&&cur->data==pre->data){
cur = cur->next;
}
ListNode* p = pre->next;
while(p!=cur){
ListNode* np = p->next;
delete p;
p = np;
}
pre->next = cur;
pre = pre->next;
if(cur!=nullptr){
cur = cur->next;
}
}
}
delete suphead;
return head;
}
};
int main(){
List list1;
cout<<list1<<endl;
Solution solution;
ListNode* head = solution.deleteDuplicates(list1.getHead()->next);
while(head!=nullptr){
cout<<head->data<<" ";
head = head->next;
}
}
我这里还是习惯性的建立了一个虚节点方便处理。
但其实这题并不需要。