Remove Duplicates from Sorted List
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given1->1->2
, Return1->2
.
Given1->1->2->3->3
, Return1->2->3
.
Ideas:
(1) Remove duplicate elements from sorted linked lists.
(2) First, empty the first-hand node. If it is null, null is returned. If it is not null, set first to point to head.
(3) second, judge whether second of the subsequent nodes of first is null. If not, compare whether their values are the same. If the value is different, the node first points to second,
Second points to the next node of the first node, and the loop continues. If the value is the same, set the last node to the next node of the second node. If the last node is not empty, and the last value
The value is the same as the value of first (indicating that the value of three consecutive nodes is the same), and last points to its subsequent nodes until the ast is empty or the value of first is different from the value of last,
If the last value is not empty, the subsequent nodes of first are last, first is last, and second is next to first. The loop continues. If the last value is empty, it indicates that
Traverse to the last node. The next node of the first node points to null and the head is returned.
(4) The pointing process can be as follows:
Example: 1-> 1-> 2-> 3-> 3-> 4-> 5-> 5
(A) first = 1, second = 1, first = second, then last = 2, because first! = Last, so first = 2, second = 3;
(B) first = 2, second = 3, first! = Second, then first = 3, second = 3;
(C) first = 3, second = 3, first = second, then last = 3, because first = last, loops until last = null or first! = Last. If last = 4, first = 4, second = 5;
(D) first = 4, second = 5, first! = Second, then first = 5, last = 5;
(E) first = 5, last = 5, first = second, last = 5, because first = last, loops until last = null or first! = Last. If last = null, first. next = null. head is returned.
The algorithm code is implemented as follows:
public ListNode deleteDuplicates(ListNode head) { if (head == null)return null;ListNode first = head;ListNode second = first.next;while (second != null) {if (first.val == second.val) {ListNode last = second.next;while (last != null && first.val == last.val) {last = last.next;}if (last != null) {first.next = last;first = last;second = first.next;} else {first.next=null;return head;}} else {first = second;second = first.next;}}return head;}