Remove Duplicates from Sorted List

Problem:

Given a sorted linked list, delete all duplicates such that each element appear only once.

Example
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

Leetcode link
Lintcode link

Solution:

This is an eassy proble, just go through the list, and remove the node whose value equals the value of previous node.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/*************************************************************************
> File Name: RemoveDuplicatesfromSortedList.java
> Author: Yao Zhang
> Mail: psyyz10@163.com
> Created Time: Mon 16 Nov 17:23:00 2015
************************************************************************/


public class RemoveDuplicatesfromSortedList{
public ListNode deleteDuplicates(ListNode head) {
if (head == null) return null;

ListNode prev = head;

while (prev.next != null){
if (prev.next.val != prev.val){
prev = prev.next;
} else {
prev.next = prev.next.next;
}
}

return head;
}
}