HF_Cherish

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

1. Question

给定有序链表,删除重复的,使每个元素仅出现一次。

 

2. Solution(O(n))

相似的有Remove Duplicates from Sorted Arrayremove element

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
          ListNode p = head;
        ListNode q;

        while( p !=null){
            for( q=p.next; (q!=null) && (q.val==p.val); q=q.next);
            if( q!=null)
                p.next = q;
            else
                p.next = null;
            p = p.next;
        }
        return head;
    }
}
View Code

 

posted on 2015-06-24 21:55  HF_Cherish  阅读(151)  评论(0编辑  收藏  举报