题解 | #删除有序链表中重复的元素-I#
删除有序链表中重复的元素-I
https://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79
解题思路:
该问题核心重复节点只保留一个。所以找到重复节点后,就需要继续遍历,直到重复节点的最后一个,然后把上一次的尾结点链接上该重复节点最后一个即可。
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ public ListNode deleteDuplicates (ListNode head) { // write code here if (head == null || head.next == null){ return head; } ListNode pre = head; ListNode curr = head.next; while (curr != null){ while (curr.val == pre.val){ //解决重复的问题 curr = curr.next; } pre.next = curr; //连接上重复节点的最后一个 pre = pre.next; if (curr != null) { curr = curr.next; } } return head; } }#我的求职思考#