LeetCode - 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.

Solution:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 public class Solution {
13     public ListNode deleteDuplicates(ListNode head) {
14         // Start typing your Java solution below
15         // DO NOT write main() function
16         if(head == null || head.next == null) return head;
17         ListNode cur = head.next;
18         ListNode prev = head;
19         while(cur != null){
20             ListNode runner = head;
21             while(runner != cur){
22                 if(runner.val == cur.val){
23                         prev.next = cur.next;
24                         cur = prev.next;
25                         break;
26                 }
27                 runner = runner.next;
28             }
29             if(runner == cur){
30                 prev = cur;
31                 cur = cur.next;
32             }    
33         }
34         return head;
35     }
36 }

 

posted @ 2013-01-30 16:41  cradle  阅读(148)  评论(0编辑  收藏  举报