• (Java) LeetCode 83. Remove Duplicates from Sorted List —— 删除排序链表中的重复元素


    Given a sorted linked list, delete all duplicates such that each element appear only once.

    Example 1:

    Input: 1->1->2
    Output: 1->2

    Example 2:

    Input: 1->1->2->3->3
    Output: 1->2->3
    

    很简单的链表问题,可以写成递归和迭代两种形式。具体思路:

    第一步,寻找第一个节点值和当前表头所指的节点值不同的节点;

    第二步,让当前表头节点的next指向找到的节点;

    第三部,递归调用前两步,或迭代调用前两步。

    详细代码注解见下。


    递归解法(Java)

    /**
     * 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 cur = head.next; //设定指针指向表头后的第一个节点
            while (cur != null && cur.val == head.val) cur = cur.next; //第一步,寻找第一个节点值和当前表头节点所指节点值不同的节点
            head.next = deleteDuplicates(cur); //找到后,进行第二步,即让当前表头节点的next指向刚才找到的节点。这里用了递归调用,上面找到的不重复节点是cur,那么这个递归返回的恰恰是cur,且同时执行以cur为节点头的去重工作
            return head; //返回头结点
        }
    }

    迭代解法(Java)

    /**
     * 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 pre = head, cur = head.next; //定义两个指针分别指向当前头节点和其下一个节点
            while (cur != null) {
                if (cur.val == pre.val) cur = cur.next; //第一步,寻找第一个非重复节点
                else { 
                    pre.next = cur; //找到后进行第二步,即让当前节点pre的next指向找到的节点cur
                    pre = cur; //之后重复之前的过程
                    cur = pre.next; 
                }
            }
            pre.next = cur; //迭代到最后因为cur为null的时候就跳出循环了,没有执行最后的去重,所以加一句让链表末尾没有重复节点
            return head;
        }
    }
  • 相关阅读:
    5月18日InterlliJ IDea快捷键
    5月17日-集合构架Collection学习
    十一java作业1
    十一java作业2
    第一周,java模拟ATMdos界面程序源代码及感想
    8.27-9.2第八周
    8.20-8.26第七周
    8.13-8.19第六周
    8.6-8.12第五周
    7.30-8.5第四周
  • 原文地址:https://www.cnblogs.com/tengdai/p/9253375.html
Copyright © 2020-2023  润新知