目录
删除有序链表中重复的元素-I(输出不重复的)
描述
删除给出链表中的重复元素(链表中元素从小到大有序),使链表中的所有元素都只出现一次
例如:
给出的链表为1→1→2,返回1→2.
给出的链表为1→1→2→3→3,返回1→2→3.
数据范围:链表长度满足 0≤n≤100,链表中任意节点的值满足 ∣val∣≤100
进阶:空间复杂度 O(1),时间复杂度 O(n)
示例1
输入:{1,1,2}
返回值:{1,2}
示例2
输入:{}
返回值:{}
JavaScript题解:
/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
*
* @param head ListNode类
* @return ListNode类
*/
function deleteDuplicates( head ) {
// write code here
if(!head) return
cur = head
while(cur&&cur.next){
if(cur.val==cur.next.val){
cur.next = cur.next.next
}else{
cur = cur.next
}
}
return head
}
module.exports = {
deleteDuplicates : deleteDuplicates
};
python题解:
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head ListNode类
# @return ListNode类
#
class Solution:
def deleteDuplicates(self , head: ListNode) -> ListNode:
# write code here
if not head: return
cur = head
while cur and cur.next:
if cur.val == cur.next.val:
cur.next = cur.next.next
else:
cur = cur.next
return head
删除有序链表中重复的元素-II(不输出重复的)
描述
给出一个升序排序的链表,删除链表中的所有重复出现的元素,只保留原链表中只出现一次的元素。
例如:
给出的链表为1→2→3→3→4→4→5, 返回1→2→5.
给出的链表为1→1→1→2→3, 返回2→3.
数据范围:链表长度 0≤n≤10000,链表中的值满足 ∣val∣≤1000
要求:空间复杂度 O(n),时间复杂度 O(n)
进阶:空间复杂度 O(1),时间复杂度 O(n)
示例1
输入:{1,2,2}
返回值:{1}
示例2
输入:{}
返回值:{}
JavaScript题解:
// function ListNode(x){
// this.val = x;
// this.next = null;
// }
/**
*
* @param head ListNode类
* @return ListNode类
*/
function deleteDuplicates( head ) {
if(!head){
return head
}
let dummy = new ListNode(0)
dummy.next = head
let cur = dummy
while(cur.next&&cur.next.next){
if(cur.next.val===cur.next.next.val){
let val = cur.next.val
while(cur.next&&cur.next.val == val){
cur.next =cur.next.next
}
}else{
cur = cur.next
}
}
return dummy.next
// write code here
}
module.exports = {
deleteDuplicates : deleteDuplicates
};
python题解:
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head ListNode类
# @return ListNode类
#
class Solution:
def deleteDuplicates(self , head: ListNode) -> ListNode:
# write code here
if not head: return None
res = ListNode(0)
res.next = head
fa = res
cur = head
while cur and cur.next:
if cur.val != cur.next.val:
fa = cur
cur = cur.next
else:
while cur.val==cur.next.val:
cur = cur.next
if not cur.next:
break
fa.next =cur.next
cur =cur.next
return res.next