LeetCode86-remove-duplicates-from-sorted-list-ii

Title description

Given a sorted linked list, delete all repetitive elements in the linked list, and keep only the elements that appear only once in the original linked list.
For example: the
given list is 1-> 2-> 3-> 3-> 4-> 4-> 5, return 1-> 2-> 5. The
given list is 1-> 1-> 1-> 2-> 3, return 2-> 3.

Code

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode deleteDuplicates(ListNode head) {
       if(head == null){return null;}
       ListNode dummy = new ListNode(0);
       
       ListNode pre = dummy;
       ListNode cur = head;    
       ListNode real = dummy;
       
       while(cur != null){
           if((pre == dummy ||pre.val != cur.val)&&(cur.next == null ||cur.val != cur.next.val)){
               real.next = cur;
               real = cur;
           }
           pre = cur;
           cur = cur.next;
           pre.next = null;
       }
        
       return dummy.next;
    }
}
Published 72 original articles · praised 0 · visits 713

Guess you like

Origin blog.csdn.net/weixin_40300702/article/details/105564318