题解 | #删除有序链表中重复的元素-I#
删除有序链表中重复的元素-I
https://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79
public class Solution { /** * 删除有序链表中的重复元素 * @param head ListNode类 * @return ListNode类 */ public ListNode deleteDuplicates(ListNode head) { if (head == null) { return null; } ListNode current = head; while (current != null && current.next != null) { if (current.val == current.next.val) { current.next = current.next.next; // 删除重复的节点 } else { current = current.next; // 移动到下一个节点 } } return head; } /** * 根据数组创建链表 * @param values 整数值数组 * @return 链表头节点 */ public ListNode DefaultListNode(Integer[] values) { if (values == null || values.length == 0) { return null; } ListNode head = new ListNode(values[0]); ListNode current = head; for (int i = 1; i < values.length; i++) { current.next = new ListNode(values[i]); current = current.next; } return head; } }
- 集合.toArray(new Integer[0])
- Arrays.sort(数组);
public ListNode deleteDuplicates1(ListNode head) { ListNode temp = head; while (temp != null && temp.next != null) { if (temp.next != null && temp.val == temp.next.val) { temp.next = temp.next.next; } else { temp = temp.next; } } return head; }
1. 删除代码是pre.next=pre.next.next。
2. 通过一个指针拿到自己指向和下一个指向对比。有一样就继续对比。没有的话就是继续走。