83. Remove Duplicates from Sorted List

来源:互联网 发布:mac放大窗口的快捷键 编辑:程序博客网 时间:2024/05/16 08:08

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; } * } */class Solution {    public ListNode deleteDuplicates(ListNode head) {        ListNode pre = new ListNode(Integer.MAX_VALUE);        ListNode tmp = pre;        while (head != null){            if (head.val == pre.val){                head = head.next;                continue;            }            pre.next = head;            pre = head;            head = head.next;        }        pre.next = head;        return tmp.next;    }}

这个解法还是不够严谨,因为链表中第一个元素可能为Integer.MAX_VALUE,会导致判断出错,为了严谨,可以先判断第一个元素值是否满足条件,从第二个元素开始做比较即可。


原创粉丝点击