【LeetCode】 82. Remove Duplicates from Sorted List II 删除排序链表中的重复元素 II(Medium)(JAVA)
题目地址: https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
题目描述:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Return the linked list sorted as well.
Example 1:
Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:
Input: 1->1->1->2->3
Output: 2->3
题目大意
给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。
解题方法
1、查看后一个元素是否和当前元素相同,如果相同遍历到不相同为止
2、出现相同遍历结束后,继续判断下一个是否重复
3、需要每次设置 pre.next = null
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode res = new ListNode(0);
ListNode pre = res;
while (head != null) {
int val = head.val;
if (head.next != null && head.next.val == val) {
while (head != null && head.val == val) {
head = head.next;
}
continue;
}
pre.next = head;
pre = head;
head = head.next;
pre.next = null;
}
return res.next;
}
}
执行用时 : 1 ms, 在所有 Java 提交中击败了 95.33% 的用户
内存消耗 : 39.5 MB, 在所有 Java 提交中击败了 5.22% 的用户