83_删除排序链表中的重复元素
83_删除排序链表中的重复元素
package 链表; /** * https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/ * * @author Huangyujun 题意:存在一个按升序排列的链表 */ public class _83_删除排序链表中的重复元素 { // 递归实现 public ListNode deleteDuplicates(ListNode head) { if (head == null || head.next == null) { return head; } else { head.next = deleteDuplicates(head.next); return head.val == head.next.val ? head.next : head; } } // 思路跟官网一样的,就是写啰嗦了 public ListNode deleteDuplicates2(ListNode head) { // 头为空,或 只有一个头结点时 if (head == null || head.next == null) return head; // 递归得到头之后的链表 ListNode pre = deleteDuplicates2(head.next); if (pre == null) return head; // 或者链表只有一个头结点时 if (pre.next == null) { if (pre.val == head.val) { // 解释一下,为什么不能return head; // 若 return head; 的话,而原来head 还指着老链条,出现重复结点啦 return pre; } else { head.next = pre; } } else { if (pre.val == head.val) { head.next = pre.next; } else { head.next = pre; } } return head; } //遍历删除 public ListNode deleteDuplicates3(ListNode head) { if (head == null) { return head; } ListNode cur = head; while (cur.next != null) { if (cur.val == cur.next.val) { cur.next = cur.next.next; } else { cur = cur.next; } } return head; } }
本文来自博客园,作者:一乐乐,转载请注明原文链接:https://www.cnblogs.com/shan333/p/15709084.html