/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
/* 递归实现 :
1. 终止条件:当head为最后一个节点,不会重复,则返回;
2. 一次递归的任务:head.next指向一个已经去重的链表,判断head节点的值和去重链表首个节点(head.next)的值是否相等,若相等,则删除head.next节点
3. 返回值: 返回已经去重的头节点*/
public ListNode deleteDuplicates(ListNode head) {
if(head == null || head.next == null)
return head;
head.next = deleteDuplicates(head.next);
if(head.val == head.next.val) head.next = head.next.next;
return head;
}
// 迭代
public ListNode deleteDuplicates(ListNode head) {
if(head == null) return null;
ListNode cur = head.next;
ListNode res = head;
int val = head.val;
while(cur != null) {
if(val == cur.val) { // 如果值相等,则删除当前节点
res.next = cur.next;
} else { // 否则更新当前值,并保存当前节点
val = cur.val;
res = res.next;
}
cur = cur.next;
}
return head;
}
}