Java-LeetCode82. 删除排序链表中的重复元素 II-伪结点&双指针
删除有序链表中重复出现的元素
http://www.nowcoder.com/questionTerminal/71cef9f8b5564579bf7ed93fbe0b2024
- 算法
- 1.设置伪结点,方便处理
- 2.双指针prev和curr
- 3.当遇到当前节点值和下一节点值相等的节点时,进行while循环找到下一个不相等的节点,挂到prev节点上
- 4.当遇到当前节点值和下一节点值不相等的节点时,prev和curr都移动到下一个节点接着遍历就行
public ListNode deleteDuplicates(ListNode head) { ListNode dummy = new ListNode(-1); dummy.next = head; ListNode prev = dummy; ListNode curr = head; while (curr != null && curr.next != null) { if (curr.val == curr.next.val) { ListNode temp = curr.next; while (temp != null && temp.val == curr.val) { temp = temp.next; } prev.next = temp; curr = temp; } else { prev = prev.next; curr = curr.next; } } return dummy.next; }
LeetCode题解 文章被收录于专栏
测试