83. Remove Duplicates from Sorted List Java solutions

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.

 

Subscribe to see which companies asked this question

 
 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) return null;
12         int tmp = -1000000;
13         ListNode res = new ListNode(-1);
14         res.next = head;
15         ListNode pre = res;
16         head = res;
17         while(head.next != null){
18             if(tmp == head.next.val)
19                 head.next = head.next.next;
20             else{
21                 tmp = head.next.val;
22                 head = head.next;
23                 pre.next = head;
24                 pre = pre.next;
25                 
26             }
27         }
28         return res.next;
29     }
30 }

 

posted @ 2016-04-21 15:03  Miller1991  阅读(152)  评论(0编辑  收藏  举报