82. 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.
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
思路:
题目意思是移除所有重复过的节点,做法就是得要找到当前节点和下一个节点不相同的节点,然后把链表接上,跳过重复的节点。
代码:
java:
代码语言:javascript复制/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null) return head;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prv = dummy, cur = dummy.next;
while (cur != null) {
while(cur.next != null && cur.next.val == cur.val) cur = cur.next;
if (prv.next == cur) {
prv = prv.next;
} else {
prv.next = cur.next; // 因为cur代表的是当前节点和下一个节点不相同所以cur有可能是重复元素
}
cur = cur.next;
}
return dummy.next;
}
}