Remove Duplicates from Sorted List

2014-11-24 09:38:58 · 作者: · 浏览: 0

题目原型:

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.

基本思路:

这题比较简单,扫描一遍链表基本上就出来了。

public ListNode deleteDuplicates(ListNode head) {
        if(head==null)
        return null;
        ListNode pre,p;
        int temp = 0;
        int flag = 0;
        p = head;
        pre = head;
        if(p!=null)
            temp = p.val;
        p = p.next;
        while(p!=null)
        {
            if(p.val!=temp)
            {
                flag = 1;
                pre.next = p;
                pre = p;
                temp = p.val;
            }
            else
                flag = 0;
            p = p.next;
        }
        if(flag==0&&pre!=null)
            pre.next = null;
        return head;
    }