原题链接:https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/
这道题目级别为 Easy,做起来也确实非常 easy。
/**
* Created by clearbug on 2018/2/26.
*/
public class Solution {
static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public static void main(String[] args) {
Solution s = new Solution();
// test 1
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(1);
ListNode node3 = new ListNode(2);
node1.next = node2;
node2.next = node3;
s.printList(node1);
s.printList(s.deleteDuplicates(node1));
// test 2
ListNode node21 = new ListNode(1);
ListNode node22 = new ListNode(1);
ListNode node23 = new ListNode(2);
ListNode node24 = new ListNode(3);
ListNode node25 = new ListNode(3);
node21.next = node22;
node22.next = node23;
node23.next = node24;
node24.next = node25;
s.printList(node21);
s.printList(s.deleteDuplicates(node21));
// test 3
ListNode node31 = new ListNode(1);
ListNode node32 = new ListNode(2);
node31.next = node32;
s.printList(node31);
s.printList(s.deleteDuplicates(node31));
}
public ListNode deleteDuplicates(ListNode head) {
ListNode currentNode = head;
ListNode preNode = head;
while (currentNode != null) {
if (currentNode.val == preNode.val) {
currentNode = currentNode.next;
} else {
preNode.next = currentNode;
preNode = currentNode;
currentNode = currentNode.next;
}
}
if (preNode != null) {
preNode.next = null;
}
return head;
}
private void printList(ListNode head) {
while (head != null) {
System.out.print(head.val + ", ");
head = head.next;
}
System.out.println();
}
}