Technology Sharing

Deduplication of ordered linked lists

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Delete duplicate elements in the linked list, and keep one duplicate element

p1   p2
1 -> 1 -> 2 -> 3 -> 3 -> null

p1.val == p2.val then delete p2, note that p1 remains unchanged

p1   p2
1 -> 2 -> 3 -> 3 -> null

p1.val != p2.val then p1, p2 move backwards

       p1   p2
1 -> 2 -> 3 -> 3 -> null
         
              p1   p2
1 -> 2 -> 3 -> 3 -> null   

p1.val == p2.val then delete p2

              p1   p2
1 -> 2 -> 3 -> null 

When p2 == null, exit the loop

Code

  1. public ListNode deleteDuplicates(ListNode head) {
  2. // 链表节点 < 2
  3. if (head == null || head.next == null) {
  4. return head;
  5. }
  6. // 链表节点 >= 2
  7. ListNode p1 = head;
  8. ListNode p2;
  9. while ((p2 = p1.next) != null) {
  10. if (p1.val == p2.val) {
  11. p1.next = p2.next;
  12. } else {
  13. p1 = p1.next;
  14. }
  15. }
  16. return head;
  17. }

No duplicate elements are retained.

p1 is the previous node to be deleted, and the values ​​of p2 and p3 are compared in each loop.

  • If the values ​​of p2 and p3 are repeated, p3 will continue to move backward until a node that does not repeat with p2 is found, and p1 points to p3 to complete the deletion.

  • If the values ​​of p2 and p3 are not repeated, p1, p2, and p3 are shifted backwards by one position, and the above operation is continued.

  • If p2 or p3 is null, exit the loop

    • When p2 is null, for example, the linked list is 1 1 1 null

 

p1 p2 p3
s,  1,   1, 1, 2, 3, null

p1 p2    p3
s,   1,    1, 1, 2, 3, null

p1 p2        p3
s,   1, 1, 1, 2, 3, null

p1 p3
s,   2, 3, null

p1 p2 p3
s,   2,  3, null

   p1 p2 p3
s, 2, 3, null

Code

  1. public ListNode deleteDuplicates(ListNode head) {
  2. if (head == null || head.next == null) {
  3. return head;
  4. }
  5. ListNode s = new ListNode(-1, head);
  6. ListNode p1 = s;
  7. ListNode p2;
  8. ListNode p3;
  9. while ((p2 = p1.next) != null && (p3 = p2.next) != null) {
  10. if (p2.val == p3.val) {
  11. while ((p3 = p3.next) != null
  12. && p3.val == p2.val) {
  13. }
  14. p1.next = p3;
  15. } else {
  16. p1 = p1.next;
  17. }
  18. }
  19. return s.next;
  20. }