83. Remove duplicate elements in the sorted list
There is a linked list arranged in ascending order. Give you the head node of this linked list. Please delete all the repeated elements so that each element only appears once.
Return a linked list of results also in ascending order.
Example 1:
Input: head = [1,1,2]
Output: [1,2]
Example 2:
Input: head = [1,1,2,3,3]
Output: [1,2,3]
prompt:
The number of nodes in the linked list is within the range [0, 300]
-100 <= Node.val <= 100 The
question data ensures that the linked list has been arranged in ascending order
This question is simpler than yesterday's. Yesterday and that time delete all the same (can be understood as deleting all), but today's only need to delete the remaining one, that is to say (no duplicate numbers)
/**
* 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) {
if (head == null) {
return head;
}
ListNode cur = head;
while (cur.next != null) {
if (cur.val == cur.next.val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return head;
}
}