Remove Duplicates from Sorted List

 

 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.

思路:

  两个指针标示

我的代码:

public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head == null)    return null;
        ListNode dummy = new ListNode(-1);
        ListNode pre = head;
        ListNode cur = head.next;
        dummy.next = pre;
        while(cur != null)
        {
            if(pre.val == cur.val)
            {
                cur = cur.next;
            }
            else
            {
                pre.next = cur;
                pre = cur;
                cur = cur.next;
            }
        }
        pre.next = null;
        return dummy.next;
        
    }
}
View Code

学习之处:

  链表问题,注意结尾处细节。

posted on 2015-03-07 09:06  zhouzhou0615  阅读(121)  评论(0编辑  收藏  举报

导航