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.

一道基本的链表操作题,注意head==null的情况,代码如下:

/**
 * 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) {
        if(head==null){
            return null;
        }
        int temp = head.val;
        ListNode p = head;
        while(p.next!=null){
            if(p.next.val==temp){
                p.next = p.next.next;
            }
            else{
                p = p.next;
                temp = p.val;
            }
        }
        return head;
    }
}

 

posted @ 2015-02-05 13:00  mrpod2g  阅读(105)  评论(0编辑  收藏  举报