作者:yvli心语 | 来源:互联网 | 2024-10-17 21:44

目录
一、题目
1、题目描述
2、基础框架
3、原题链接
二、解题报告
1、思路分析
2、代码详解
三、本题小知识
一、题目
1、题目描述
给定一个已排序的链表的头 head
, 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
示例 1:

输入:head = [1,1,2]
输出:[1,2]
示例 2:

输入:head = [1,1,2,3,3]
输出:[1,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 83. 删除排序链表中的重复元素
二、解题报告
1、思路分析
(1)递归
- 若值相同则 head=deleteDuplicates(head.next);
- 不同则向后移再 head.next=deleteDuplicates(head.next);
(2)指针遍历
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=deleteDuplicates(head.next);// }else{// head.next=deleteDuplicates(head.next);// }// return head;//指针遍历,删除相同结点ListNode res = head;if(head==null){return null;}while(res.next!=null){//res结点和他的后一个结点相同,则把res后一个的后有一个结点千移覆盖res的下一个结点if(res.val==res.next.val){res.next=res.next.next;//不相等则指针后移}else{res=res.next;}}return head;}
}
三、本题小知识
三数之和,枚举;
