本文共 980 字,大约阅读时间需要 3 分钟。
示例 1:
输入: 1->1->2
输出: 1->2 示例 2:输入: 1->1->2->3->3
输出: 1->2->31.自己的尝试,完美通过
class Solution { public ListNode deleteDuplicates(ListNode head) { if(head == null) return null; ListNode fake = new ListNode(-1); fake.next = head; ListNode cur = fake.next, pre = fake; while(cur != null){ while(cur.next != null && cur.val == cur.next.val){ cur = cur.next; } pre.next = cur; pre = cur; cur = cur.next; } return fake.next; }}
2.利用一个指针也可以实现
class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode cur = head; while(cur != null && cur.next != null){ if(cur.val == cur.next.val) { cur.next = cur.next.next; }else{ cur = cur.next; } } return head;//这里直接保留头结点即可,因为即使有重复也没有被删除 }}
转载地址:http://gpvp.baihongyu.com/