LeetCode Remove Duplicates from Sorted List & Remove Duplicates from Sorted List II
来源:互联网 发布:毕向东java反射 编辑:程序博客网 时间:2024/05/01 21:44
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;}}
0 0
- LeetCode: Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- LeetCode: Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- [LeetCode]Remove Duplicates from Sorted List II
- [leetcode]Remove Duplicates from Sorted List II
- LeetCode-Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- LeetCode - Remove Duplicates from Sorted List II
- LeetCode | Remove Duplicates from Sorted List II
- LeetCode:Remove Duplicates from Sorted List II
- 【leetcode】Remove Duplicates from Sorted List II
- Leetcode: Remove Duplicates from Sorted List II
- leetcode Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List II
- Dubbo之旅--集群容错和负载均衡
- [转] 常用牛人主页链接(计算机视觉、模式识别、机器学习相关方向)
- SpringMVC第一次搭建
- python 简单图像处理(13)
- 文章标题
- LeetCode Remove Duplicates from Sorted List & Remove Duplicates from Sorted List II
- 互联网推送服务原理:长连接+心跳机制
- Think In Python Exercise
- 关于VC++6.0中的字符串拼接函数strcat
- J2EE的13规范之我见
- UIPickerView 选取器(滚轮)—IOS开发
- 黑马程序员——Java基础---网络编程
- 教你如何挣脱天朝枷锁,访问Google
- UML类图中的关系