您的位置:首页 > 其它

LeetCode 82. Remove Duplicates from Sorted List II 链表 & 83

2016-02-27 16:58 344 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: