[leedcode 83] 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.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        //两种解法:
        //一种声明三个节点,一个代表index之前的均满足要求,first是遍历的节点,pre是first的前置,便于删除节点时保留前置
        //一种是只需要一个节点,该节点和其后置值进行比较,如果相等,直接删除,如果不等指向下一节点
        if(head==null||head.next==null) return head;
      /*  ListNode pre=head;
        ListNode first=head.next;
        ListNode index=head;
        while(first!=null){
            if(index.val==first.val){
                pre.next=first.next;
                first=first.next;
            }else{
                pre=first;
                first=first.next;
                index=index.next;
            }
        }
        return head;*/
        ListNode pre=head;
        while(pre.next!=null){
            if(pre.next.val==pre.val){
                pre.next=pre.next.next;
            }else{
                pre=pre.next;
            }
        }
        return head;
    }
}

 

posted @ 2015-07-15 12:03  ~每天进步一点点~  阅读(124)  评论(0编辑  收藏  举报