删除有序链表中的重复元素(python)
重复的留下一个
def deleteDuplicates(self , head: ListNode) -> ListNode:
# write code here
#空链表
if head == None:
return None
#遍历指针
cur = head
#指针当前和下一位不为空
while cur and cur.next:
#如果当前与下一位相等则忽略下一位
if(cur.val == cur.next.val):
cur.next = cur.next.next
#否则指针正常遍历
else:
cur = cur.next
return head
重复的不留
def deleteDuplicates(self , head: ListNode) -> ListNode:
# write code here
#空链表
if head == None:
return None
res = ListNode(0)
#在链表前加一个表头
res.next = head
cur = res
while cur.next and cur.next.next:
#遇到相邻两个节点值相同
if cur.next.val == cur.next.next.val:
temp = cur.next.val
#将所有相同的都跳过
while cur.next != None and cur.next.val == temp:
cur.next = cur.next.next
else:
cur = cur.next
#返回时去掉表头
return res.next
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~