/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode deleteDuplication(ListNode pHead)
{
if(pHead==null||pHead.next==null) return pHead;
if(pHead.val==pHead.next.val){
ListNode node=pHead.next;
while(node!=null&&node.val==pHead.val){
// 跳过值与当前节点相同的全部节点,找到第一个与当前节点不同的节点
node=node.next;
}
return deleteDuplication(node);// 从第一个与当前结点不同的结点继续递归
}
else{
// 保留当前节点,从下一个节点继续递归
pHead.next=deleteDuplication(pHead.next);
return pHead;
}
}
}
递归法:
/**
* 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;
head.next=deleteDuplicates(head.next);
return head.val==head.next.val?head.next:head;
}
}
/**
* 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) return head;
ListNode tmp=head; //假的头结点
while(head!=null&&head.next!=null){
if(head.val==head.next.val){
head.next=head.next.next;
}
else{
head=head.next;
}
}
return tmp;
}
}