zoukankan      html  css  js  c++  java
  • LeetCode83- Remove Duplicates from Sorted List-Easy

    删除链表中的重复结点:

    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结点值相同,那么就把当前结点的 next 指针跳过紧挨着的相同值的结点,指向后面一个结点(cur.next = cur.next.next),不移动当前指针。

    如果当前结点与它next结点值不同,那么就向后移动指针。

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
        public ListNode deleteDuplicates(ListNode head) {
            
            ListNode cur = head;
            
            while(cur != null && cur.next != null) {
                if(cur.val == cur.next.val) {
                    // 不移动cur
                    cur.next = cur.next.next;
                } else {
                    cur = cur.next;
                }
            }
            
            return head;
        }
    }

    解法二:

    递归法

    Base case:只有一个结点或空链表则返回头结点

    对 head 后面的结点调用递归函数,那么就应该 suppose 返回来的链表就已经没有重复项了,此时接到 head 结点后面。

    return检查head 和head.next 是否有duplicate。

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    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;
        }
    }
  • 相关阅读:
    jenkins 项目部署方式二
    java 消息机制 ActiveMQ入门实例
    图片验证码大全
    Java列表分页查询结果导出到CSV文件,导入CSV文件并解析
    PHP之数组array
    JDK运行.Jar文件的控制台命令是什么
    ireport开发报表,Java和JSP端如何集成
    java Map及Map.Entry详解
    MFC
    Syms函数
  • 原文地址:https://www.cnblogs.com/Jessiezyr/p/12963083.html
Copyright © 2011-2022 走看看