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的时候把返回值删除
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;
}
};
这种题,还是写个头结点把,写头结点会更顺,很多细节都不用考虑了,然后记得最后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;
}
};
相关文章推荐
- Android Kotlin入门-基本类型
- 十大OpenGL教程
- TCP异步聊天
- 爬虫网页编码问题解决思路
- 中国剩余定理
- ThreadLocal 的简单应用
- TCPdump抓包命令详解
- 《Unity_API解析》 第四章 HideFlags类
- HDU 5634 Rikka with Phi(暴力、线段树)
- 继承中子父类构造函数的问题
- 文章标题
- Linux 常用命令汇总--加了注释
- linux系统中mysql数据库的导入和导出
- uva 1152 4 Values whose Sum is 0 map会超时
- 设计模式之六大原则
- cocos2d-x-bug集
- powershell 1.2 windows-server
- 【四圣龙神录的编程教室】第23章、来制作决死炸弹吧
- codeforces 633A A. Ebony and Ivory(暴力)
- java中接口实现的大概标准格式