问题:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
解决:
① 只要有重复,就删除包含重复值的节点。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {//1ms
public ListNode deleteDuplicates(ListNode head) {
ListNode header = new ListNode(-1);
header.next = head;
ListNode pre = header;
while(pre.next != null && pre.next.next != null){
if(pre.next.val == pre.next.next.val){
int tmp = pre.next.val;
while(pre.next != null && pre.next.val == tmp){
pre.next = pre.next.next;
}
}else{
pre = pre.next;
}
}
return header.next;
}
}