博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
83. 移除已排序链表中重复的节点 Remove Duplicates from Sorted List
阅读量:4573 次
发布时间:2019-06-08

本文共 1014 字,大约阅读时间需要 3 分钟。

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.

移除单链表中重复的节点

 
  1. public class Solution {
  2. public ListNode DeleteDuplicates(ListNode head) {
  3. if (head == null)
  4. {
  5. return null;
  6. }
  7. ListNode node = head;
  8. ListNode nextNode = null;
  9. while (node.next != null)
  10. {
  11. if (node.val == node.next.val)
  12. {
  13. nextNode = node.next;
  14. while (nextNode.val == node.val)
  15. {
  16. if (nextNode.next == null)
  17. {
  18. node.next = null;
  19. return head;
  20. }
  21. else
  22. {
  23. nextNode = nextNode.next;
  24. }
  25. }
  26. node.next = nextNode;
  27. node = nextNode;
  28. }
  29. else
  30. {
  31. node = node.next;
  32. }
  33. }
  34. return head;
  35. }
  36. }
 
  1. public class Solution {
  2. if (head == null) return head;
  3. ListNode node = head;
  4. while (node.next != null)
  5. {
  6. if (node.val == node.next.val)
  7. {
  8. node.next = node.next.next;
  9. }
  10. else
  11. {
  12. node = node.next;
  13. }
  14. }
  15. return head;
  16. }
  17. }

大牛的递归版本

https://discuss.leetcode.com/topic/14775/3-line-java-recursive-solution

转载于:https://www.cnblogs.com/xiejunzhao/p/cf812aceadb80e2c2282e44ea1ad7172.html

你可能感兴趣的文章
获取当前地址的参数值
查看>>
基于bs4库的HTML内容查找方法
查看>>
Ubuntu安装TTF字体
查看>>
使用YII缓存注意事项
查看>>
Office转HTML
查看>>
Ping 命令的使用方法总结
查看>>
python基础--01安装
查看>>
Spring boot配置mybatis多数据源
查看>>
获取系统的相关文件夹
查看>>
PAT-乙级-1008. 数组元素循环右移问题 (20)
查看>>
OpenCV 传统分割测试
查看>>
Springboot拦截器线上代码失效
查看>>
WCF初探-2:手动实现WCF程序
查看>>
好程序员技术分享html5和JavaScript的区别
查看>>
好程序员web前端分享CSS3文本属性
查看>>
ThinkPHP3.0启动过程
查看>>
Java入门 之 类和对象(一) - 类
查看>>
16级第二周寒假作业E题
查看>>
Java实现Windows锁屏
查看>>
在线会话管理
查看>>