Reprint Please specify source: Z_zhaojun's Blog
Original address: http://blog.csdn.net/u012975705/article/details/50411033
Title Address: https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
Remove duplicates from Sorted List II
Given a sorted linkedList, delete AllNodes that has duplicate numbers, leaving only distinct numbers from the originalList.For Example,given1 -2 -3 -3 -4 -4 -5,return 1 -2 -5.Given1 -1 -1 -2 -3,return 2 -3.
Solution (Java):
/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * ListNode ( int x) {val = x;} *} * / Public class solution { PublicListNodedeleteduplicates(ListNode head) {if(Head = =NULL|| Head.next = =NULL) {returnHead } ListNode helper =NewListNode (0); ListNode pre = helper;BooleanIsdup =false; while(Head! =NULL&& Head.next! =NULL) {if(Head.val = = Head.next.val) {isdup =true; }Else if(Isdup) {isdup =false; }Else{pre.next = head; Pre = Pre.next; } head = Head.next; }if(!isdup) {pre.next = head; Pre = Pre.next; }Else{Pre.next =NULL; }returnHelper.next; }}
leetcode:82. Remove duplicates from Sorted List II (Java) solution