您的位置:首页 > 其它

83. Remove Duplicates from Sorted List

2017-11-09 23:02 274 查看
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,会导致判断出错,为了严谨,可以先判断第一个元素值是否满足条件,从第二个元素开始做比较即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: