剑指offer-删除链表中重复的结点-链表-python ***
2024-10-07 07:39:22
题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
思路:
如果该链表当前节点与下一节点为空,则返回前当前节点。
否则,比较这两个节点的val,使用递归,
如果 当两节点值相等时,使用temp来替代 pHead.next
然后循环判断temp是否为空,若不为空,则temp指向下一节点。
如果不相等,则移动到下一节点
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplication(self, pHead):
# write code here
if not pHead or not pHead.next:
return pHead
if pHead.val == pHead.next.val:
temp = pHead.next
while temp and temp.val == pHead.val:
temp = temp.next
return self.deleteDuplication(temp)
else:
pHead.next = self.deleteDuplication(pHead.next)
return pHead
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
thead = ListNode('a')
thead.next = head
pre,cur = None,thead
while cur:
pre=cur
cur=cur.next
while cur and cur.next and cur.next.val == cur.val:
t=cur.val
while cur and cur.val==t:
cur=cur.next
pre.next=cur
return thead.next
最新文章
- 仿淘宝分页按钮效果简单美观易使用的JS分页控件
- my sql中join的操作
- De4Dot+Reflector 支持多种反混淆
- canvas 画六边形
- iis7.5错误 配置错误
- Cocos2d入门--2--三角函数的应用
- 使用sed,awk将love转换成LOVE,将CHINA转换成china
- Python:字典
- spring mvc mybatis集成踩的坑
- HTTPS与MITM
- 不高兴的o( ̄ヘ ̄o#)JJ
- javascript实现游戏贪吃蛇
- Disconnected from the target VM, address: '127.0.0.1:57178', transport: 'socket'
- [js] - 前端FileReader使用,适用于文件上传预览.(并未传入后端)
- WPF中的DoubleAnimation
- ES系列十二、ES的scroll Api及分页实例
- setBit testBit权限管理
- ElasticSearch 2 (20) - 语言处理系列之如何开始
- 1050: 贝贝的ISBN号码(isbn)
- JVM笔记(二) 垃圾收集器(1)