https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
这种题,还是写个头结点把,写头结点会更顺,很多细节都不用考虑了,然后记得最后return的时候把返回值删除
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <stack>
#include <algorithm>
#include <vector>
using namespace std;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
struct ListNode {
int val;
ListNode *next;
ListNode( int x ) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head == NULL)return head;
ListNode *ret = new ListNode(-1),*thead=ret;
while(head) {
int v= head->val;
int cnt =0;
while( (head) && (head->val == v) ) {
cnt ++;
head = head->next;
}
if(cnt <= 1) {
addNode(thead, v);
thead = thead->next;
}
}
thead = ret;
ret = ret->next;
delete thead;
return ret;
}
void addNode( ListNode* ptr, int num ) {
ptr->next = new ListNode(num);
ptr->next->next = NULL;
}
};
83 直接修改代码就OK
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head == NULL)return head;
ListNode *ret = new ListNode(-1),*thead=ret;
while(head) {
int v= head->val;
int cnt =0;
while( (head) && (head->val == v) ) {
cnt ++;
head = head->next;
}
//if(cnt <= 1) {
addNode(thead, v);
thead = thead->next;
//}
}
thead = ret;
ret = ret->next;
delete thead;
return ret;
}
void addNode( ListNode* ptr, int num ) {
ptr->next = new ListNode(num);
ptr->next->next = NULL;
}
};