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: https://leetcode-cn.com/probl… 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 || head.next == null) { return head; } ListNode next = head.next, cur = head; int curVal = head.val; while (next ! = null) { if (next.val == curVal) { next = next.next; cur.next = null; } else { cur.next = next; cur = cur.next; curVal = next.val; next = next.next; } } return head; } public static void main(String[] args) { ListNode root = new ListNode(1); root.next = new ListNode(1); root.next.next = new ListNode(2); root.next.next.next = new ListNode(3); root.next.next.next.next = new ListNode(3); System.out.println("===== is not used before processing "); ListNode temp = root; while (temp ! = null) { System.out.print(temp.val + " "); temp = temp.next; } System.out.println(); deleteDuplicates(root); System.out.println("===== processed is normal "); while (root ! = null) { System.out.print(root.val + " "); root = root.next; }}}

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