LeetCode Remove Duplicates from Sorted List & Remove Duplicates from Sorted List II
2015-06-30 22:55
399 查看
Remove Duplicates from Sorted List
Description:Given a sorted linked list, delete all duplicates such that each element appear only once.
Solution:
每次while循环,都判断当前节点与下一个节点的val是否一样,一样则改变当前节点的next指针,否则跳到下一个节点。
import java.util.*; public class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode temp = head; ListNode next; while (temp != null) { next = temp.next; if (next == null) break; if (temp.val == next.val) { temp.next = next.next; } else { temp = next; } } return head; } }
Remove Duplicates from Sorted List II
Description:Given a
sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers
from the original list.
Solution:
利用two pointer方法,每次对于当下要遍历的节点t1,都用进行另外一次遍历,记为t2,一直搜索到null或者t1和t2的val不同。如果t2是t1的next,那么就表示t1没有重复值,否则t1赋值到t2,继续遍历。
import java.util.*; public class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode t1, t2; t1 = head; t2 = head; while (t1 != null) { t2 = t1; while (t2 != null) { if (t2.val != t1.val) break; t2 = t2.next; } if (t1.next == t2) { break; } else { t1 = t2; } } head = t1; t1 = t2 = head; ListNode temp = head; while (t1 != null) { t2 = t1; while (t2 != null) { if (t2.val != t1.val) break; t2 = t2.next; } if (t1.next == t2) { temp.next = t1; temp = temp.next; System.out.println(temp.val); t1.next = null; t1 = t2; } else { t1 = t2; } } return head; } }
相关文章推荐
- 定比分点、中点公式
- python 简单图像处理(13)
- 常见小问题(待更新)
- [转] 常用牛人主页链接(计算机视觉、模式识别、机器学习相关方向)
- AndroidMainfest.xml详解——<meta-data>
- Dubbo之旅--集群容错和负载均衡
- 如何解除内容审查程序的密码
- .NET解析专题系列
- HTML5+CSS3 APP开发之 精彩H5
- Python学习之二【初学Python】
- Set Matrix Zeroes算法详解
- 手机安全卫士04
- Longest Substring Without Repeating Characters(leetcode 3)
- java构造器小结
- 欢迎使用CSDN-markdown编辑器
- 10_Android中通过HttpUrlConnection访问网络,Handler和多线程使用,读取网络html代码并显示在界面上,ScrollView组件的使用
- 10_Android中通过HttpUrlConnection访问网络,Handler和多线程使用,读取网络html代码并显示在界面上,ScrollView组件的使用
- leetcode算法刷题(五)——动态规划(三)
- 数据结构-中序转后序
- 拉格朗日插值