83. Remove Duplicates from Sorted List【easy】

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

解法一:

 /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
} ListNode * dummy = new ListNode(INT_MIN);
dummy->next = head; while (head != NULL && head->next != NULL) {
if (head->val == head->next->val) {
ListNode * temp = head->next;
head->next = temp->next;
free(temp);
}
else {
head = head->next;
}
} return dummy->next;
}
};

这里也可以不用dummy节点,之所以那么写就是为了好看而已,嘿嘿

解法二:

 public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null)return head;
head.next = deleteDuplicates(head.next);
return head.val == head.next.val ? head.next : head;
}

参考了@wen587sort 的代码,大神的代码也是受到了下面的提示:

This solution is inspired by renzid https://leetcode.com/discuss/33043/3-line-recursive-solution

题外话,关于递归,我觉得@ElayMarco 的说法很中立:

Well, on sites like these one's, I believe a lot of times people want to post 'other ways' of doing things, which is good. Recursive solutions sometimes require less coding to implement, and as a by-product of this look more clever or elegant. Recursion is just a tool. Sometimes the job calls for a hammer. Other times, a hammer is not suitable. Part of being a good programmer is knowing when to use which tools. But on sites like these, some people like to 'sharpen their tools' by writing recursive solutions to problems where iterative solutions are more efficient. Think of it as practice.

看来,还是我自己太菜了……

最新文章

  1. maven自动编译脚本
  2. poj3342Party at Hali-Bula(树形dp)
  3. Unitils集成DBUnit、Spring-单元测试
  4. cocos2d-x CCEditBox 字符不能显示完全的bug
  5. 再次阅读《精通CSS-高级Web标准解决方案(第二版)》
  6. UIwebView实现html的离线缓存
  7. RealThinClient学习(一)
  8. psy & obv
  9. mysql 主从同步 mysql代理服务器
  10. mybatis mapper.xml的特殊操作符
  11. zeppelin 一直报这个警告 也是醉了
  12. PSPnet模型结构的实现代码
  13. PAT 乙级 1067 试密码(20 分)
  14. PoseNet: A Convolutional Network for Real-Time 6-DOF Camera Relocalization
  15. 本地环境 XAMPP+phpStorm+XDebug+chrome配置和断点调试 注册方法
  16. JS实现的数组全排列输出算法
  17. 全解析jQuery插件开发!很好很强大!
  18. Web前端开发最佳实践(8):还没有给CSS样式排序?其实你可以更专业一些
  19. 【剑指offer】05替换空格,C++实现
  20. Scanner和BufferReader之区别

热门文章

  1. Codechef ForbiddenSum
  2. 【三分】Codeforces Round #403 (Div. 2, based on Technocup 2017 Finals) B. The Meeting Place Cannot Be Changed
  3. golang垃圾回收
  4. 【java】JDK安装后,没有配置环境变量,也可以java -version查看到版本信息
  5. grub
  6. JS使用cookie实现DIV提示框只显示一次的方法
  7. RHEL7.1 安装openstack juno 一个BUG
  8. Amazon EC2安装mysql多实例并配置主从复制
  9. asp.net权限控制的方式
  10. 【千纸诗书】—— PHP/MySQL二手书网站后台开发之知识点记录