题目链接:删除链表中的重复节点
分析:有序链表,双指针
/**
* 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 l = head,r = head.next;
while(r!=null){
while(r!=null&&r.val == l.val){
l.next = r.next;
r = r.next;
}
if(r!=null) {
l = l.next;
r = r.next;
}
}
return head;
}
}
变式:删除链表II
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null) return head;
if(head.val == head.next.val){
while(head!=null&&head.next!=null&&head.val == head.next.val){
head = head.next;
}
return deleteDuplicates(head.next);
}else{
head.next = deleteDuplicates(head.next);
return head;
}
}
}