Removes duplicate elements in a sorted linked list

Description: There is a linked list in ascending order. Given the head node of the linked list, please delete all duplicate elements so that each element appears only once.

Returns the resulting list, also in ascending order.

See the LeetCode website for an example.

Source: LeetCode Link:… Copyright belongs to collar network. Commercial reprint please contact the official authorization, non-commercial reprint please indicate the source.

Solution 1: linked list traversal
  • First, if head is null or if head has only one node, return head directly.
  • If the value of the next node is equal to curVal, then skip this node and continue traversing the next node. If the value of the next node is not equal to curVal, then update the value of curVal to the value of the next node. And the next node of cur is set to next, until the traversal is completed, and finally the head is returned.
public class LeetCode_083 { public static ListNode deleteDuplicates(ListNode head) { if (head == null || == null) { return head; } ListNode next =, cur = head; int curVal = head.val; while (next ! = null) { if (next.val == curVal) { next =; = null; } else { = next; cur =; curVal = next.val; next =; } } return head; } public static void main(String[] args) { ListNode root = new ListNode(1); = new ListNode(1); = new ListNode(2); = new ListNode(3); = new ListNode(3); System.out.println("===== is not used before processing "); ListNode temp = root; while (temp ! = null) { System.out.print(temp.val + " "); temp =; } System.out.println(); deleteDuplicates(root); System.out.println("===== processed is normal "); while (root ! = null) { System.out.print(root.val + " "); root =; }}}

【 Daily Message 】
I hope this long and small life does not live up to your every glorious hour.