9
#yyds干货盘点# 面试必刷TOP101:删除有序链表中重复的元素-II
source link: https://blog.51cto.com/u_15488507/5558210
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
#yyds干货盘点# 面试必刷TOP101:删除有序链表中重复的元素-II
原创1.简述:
描述给出一个升序排序的链表,删除链表中的所有重复出现的元素,只保留原链表中只出现一次的元素。例如:给出的链表为, 返回.给出的链表为, 返回.
数据范围:链表长度 ,链表中的值满足
要求:空间复杂度 ,时间复杂度
进阶:空间复杂度 ,时间复杂度
示例1{1,2,2}
2.代码实现:
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode deleteDuplicates(ListNode head) {
if(head == null){
return null;
}
if(head.next != null && head.val == head.next.val){//发现有重复值
while(head.next != null && head.val == head.next.val){
head = head.next;//删除
}
return deleteDuplicates(head.next);//把与删除的那个结点相同的结点也进行删除
}
head.next = deleteDuplicates(head.next);//当没有发现重复值的情况,就一直进行递归操作
return head;
}
}
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode deleteDuplicates(ListNode head) {
if(head == null){
return null;
}
if(head.next != null && head.val == head.next.val){//发现有重复值
while(head.next != null && head.val == head.next.val){
head = head.next;//删除
}
return deleteDuplicates(head.next);//把与删除的那个结点相同的结点也进行删除
}
head.next = deleteDuplicates(head.next);//当没有发现重复值的情况,就一直进行递归操作
return head;
}
}
- 赞
- 收藏
- 评论
- 分享
- 举报
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK