> 文档中心 > 你今天学算法了吗?打卡第十一天

你今天学算法了吗?打卡第十一天

 


目录

 一、题目

1、题目描述

2、基础框架

3、原题链接

二、解题报告

1、思路分析

2、代码详解

三、本题小知识

 


 一、题目

1、题目描述

给定一个已排序的链表的头 head , 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。

示例 1:

输入:head = [1,2,3,3,4,4,5]输出:[1,2,5]

示例 2:

输入:head = [1,1,1,2,3]输出:[2,3]

2、基础框架

   Java 版本给出的基础框架代码如下:   

/ * 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) {    }}

3、原题链接

    LeetCode  82. 删除排序链表中的重复元素 II

二、解题报告

1、思路分析

 递归出口head==null || head.next==null

如果head.val==head.next.val

 while(head.next!=null&&head.val==head.next.val){  head.next=head.next.next; }
  •         移动head.next直到出现与当前head.value不相等的情况(含null)
  •         并且此时的head已经不能要了,因为已经head是重复的节点

 

2、代码详解

/ * 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){    return null;}if(head.next==null){    return head;}      if(head.val==head.next.val){    //找到和head.val不相等的结点     while(head.next!=null&&head.val==head.next.val){  head.next=head.next.next;     }     head=deleteDuplicates(head.next);}else{     head.next=deleteDuplicates(head.next);}return head;    }}

三、本题小知识

  链表数据结构,结点删除

51银饰网