LeetCode Remove Duplicates from Sorted List
Problem
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
2
3
4
5
6
7
8
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
Java 实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.coderli.leetcode.algorithms.easy;
/**
* Given a sorted linked list, delete all duplicates such that each element appear only once.
* <p>
* For example,
* Given 1->1->2, return 1->2.
* Given 1->1->2->3->3, return 1->2->3.
*
* @author li.hzh 2017-11-09 12:43
*/
public class RemoveDuplicatesFromSortedList {
public static void main(String[] args) {
RemoveDuplicatesFromSortedList remove = new RemoveDuplicatesFromSortedList();
RemoveDuplicatesFromSortedList.ListNode first = remove.new ListNode(1);
RemoveDuplicatesFromSortedList.ListNode second = remove.new ListNode(1);
first.next = second;
second.next = remove.new ListNode(2);
print(remove.deleteDuplicates(first));
first.next = second;
second.next = remove.new ListNode(1);;
print(remove.deleteDuplicates(first));
}
public ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return head;
}
ListNode currentNode = head;
ListNode preNode = null;
while (currentNode != null) {
if (preNode == null) {
preNode = currentNode;
} else {
if (preNode.val == currentNode.val) {
preNode.next = currentNode.next;
} else {
preNode = currentNode;
}
}
currentNode = currentNode.next;
}
return head;
}
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
private static void print(RemoveDuplicatesFromSortedList.ListNode list) {
while (list != null) {
System.out.println(list.val);
list = list.next;
}
}
}
分析
没什么可过多解释的,保持好中间状态即可。
所有代码已上传至Github:https://github.com/lihongzheshuai/yummy-code
GESP 学习专题站:GESP WIKI
"luogu-"系列题目可在洛谷题库进行在线评测。
"bcqm-"系列题目可在编程启蒙题库进行在线评测。
欢迎加入:Java、C++、Python技术交流QQ群(982860385),大佬免费带队,有问必答
欢迎加入:C++ GESP/CSP认证学习QQ频道,考试资源总结汇总
欢迎加入:C++ GESP/CSP学习交流QQ群(688906745),考试认证学员交流,互帮互助
本文由作者按照 CC BY-NC-SA 4.0 进行授权
