82. Remove Duplicates from Sorted List II

网友投稿 507 2022-09-04

82. Remove Duplicates from Sorted List II

82. Remove Duplicates from Sorted List II

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example, Given 1->2->3->3->4->4->5, return 1->2->5. Given 1->1->1->2->3, return 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) { if(head == null || head.next == null) return head; ListNode newHead = new ListNode(-1); newHead.next = head; ListNode p1 = newHead; ListNode p2 = head; while(p2 != null){ boolean dup = false; while(p2.next != null && p2.val == p2.next.val){ dup = true; p2 = p2.next; } if(dup){ p2 = p2.next; continue; } p1.next = p2; p1 = p1.next; p2 = p2.next; } p1.next = p2; return newHead.next; }}

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */class Solution { public ListNode deleteDuplicates(ListNode head) { if(head == null) return null; ListNode l1 = new ListNode(0); ListNode l2, left, right; l1.next = l2 = head; left = l1; int value = 1; while(l2.next != null) { right = l2; l2 = l2.next; if(l2.val == right.val) value++; else { if(value < 2) { left.next = right; left = right; } value = 1; } } if(value < 2) left.next = l2; else left.next = null; return l1.next; }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:34.丑数
下一篇:PHP程序执行的过程原理(php执行代码的四个步骤)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~