The title

There is a linked list in ascending order, and you are given the head node of the linked list. Please delete all the nodes in the linked list that have duplicate numbers, and only keep the original list that does not have duplicate numbers. Returns a linked list of results, also in ascending order.Copy the code

The sample

Input: 1 -> 2 -> 3 -> 3 -> 4-> 4-> 5 Output: 1 -> 2 -> 5Copy the code

Code implementation

The main idea

  1. First of all, they want to delete all the duplicate elements, not keep one duplicate element
  2. Create a virtual header to build a new linked list
  3. The current node is added to the new list only when the value of the current node is not equal to the value of the next node through the original list
  4. If the value of the current node is equal to the value of the next node, update the current node through a loop
Public ListNode deleteDuplicates (ListNode head) {/ / the list only one node is null or if (the head = = null | | head. The next = = null) {return head; } ListNode dummmty = new ListNode(); ListNode tail = dummmty; while(head ! = null) {/ / head at this time. Next = = null, shows that the head is probably the last node if (head. The next = = null | | head. Val! = head.next. Val){tail.next = head; tail = tail.next; } // Update head while(head. Next! = null && head.val == head.next.val){ head = head.next; } // then update head, pointing to a non-repeating element head = head.next; } tail.next = null; return dummmty.next; }Copy the code