Topic requirements:
Given the head of a sorted linked list head
, remove all duplicate elements such that each element appears only once . Returns a sorted linked list .
Example 1:
Input: head = [1,1,2] Output: [1,2]
Problem-solving ideas:
The cur pointer points to the head. When cur.val==cur.next.val, it will be deduplicated, and the next one of cur will point to the next one of the next one, otherwise it will directly point to the next node
Code display:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode cur=head;
while(cur!=null&&cur.next!=null){
if(cur.val==cur.next.val){
cur.next=cur.next.next;
}
else{
cur=cur.next;
}
}
return head;
}
}
operation result: