题解 | #删除有序链表中重复的元素-I#
删除有序链表中重复的元素-I
https://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79
时间复杂度O(n),空间O(1)
因为链表元素有序,与有序数组删除重复元素那题类似,当没重复时更新待检查对象值就行了(数组只涉及更新值,链表更新值和前驱结点),无非一个链表操作
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * * @param head ListNode类 * @return ListNode类 */ public ListNode deleteDuplicates (ListNode head) { if (head == null || head.next==null) return head; ListNode cur = head.next; ListNode pre = head; int v = head.val; while(cur!=null){ if(v == cur.val){ pre.next = cur.next; cur = cur.next; }else{ v = cur.val; pre = cur; cur = cur.next; } } return head; } }