Remove Duplicates from Sorted List

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  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode deleteDuplicates(ListNode head) {
11         if (head == null || head.next == null) {
12             return head;
13         }
14         ListNode dummy = new ListNode(0);
15         dummy.next = head;
16         while (head != null && head.next != null) {
17             if (head.val == head.next.val) {
18                 int val = head.val;
19                 while (head.next != null && head.next.val == val) {
20                     head.next = head.next.next;
21                 }
22                 head = head.next;
23             } else {
24                 head = head.next;
25             }
26         }
27         return dummy.next;
28     }
29 }

 

posted @ 2016-08-16 09:16  YuriFLAG  阅读(110)  评论(0)    收藏  举报