博客
关于我
python去掉重复的数字_leetcode删除列表的重复元素python解法
阅读量:398 次
发布时间:2019-03-05

本文共 887 字,大约阅读时间需要 2 分钟。

题目:

给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现的数字。

示例 1:

输入: 1->2->3->3->4->4->5

输出: 1->2->5

示例 2:

输入: 1->1->1->2->3

输出: 2->3

先上自己的提交记录:

我太难了!!

解题思路:

1、新建虚拟头结点,这是为了解决头节点就和后面的节点重复的情况

2、使用两个指针pre、cur,pre指向虚拟头节点,cur指向虚拟头节点的next也即head,然后使用cur遍历链表,然后找到存在重复元素的值,再一个循环,使cur指向重复元素的最后一个,然后令pre.next = cur.next即删除了所有的重复元素。

3、小心while中访问空指针就行,最后返回结果

源代码如下:

# Definition for singly-linked list.

# class ListNode:

# def __init__(self, x):

# self.val = x

# self.next = None

class Solution:

def deleteDuplicates(self, head: ListNode) -> ListNode:

#if head is None or head.next is None

#if not head

dummy_head = ListNode(0)

dummy_head.next = head

pre = dummy_head

cur = head

while cur:

if cur.next and cur.val == cur.next.val:

while cur.next and cur.val == cur.next.val:

cur = cur.next

# cur.val != cur.next.val

pre.next = cur.next

cur = cur.next

continue

pre = pre.next

cur = cur.next

return dummy_head.next

转载地址:http://sdjg.baihongyu.com/

你可能感兴趣的文章
mysql 字段合并问题(group_concat)
查看>>
mysql 字段类型类型
查看>>
MySQL 字符串截取函数,字段截取,字符串截取
查看>>
MySQL 存储引擎
查看>>
mysql 存储过程 注入_mysql 视图 事务 存储过程 SQL注入
查看>>
MySQL 存储过程参数:in、out、inout
查看>>
mysql 存储过程每隔一段时间执行一次
查看>>
mysql 存在update不存在insert
查看>>
Mysql 学习总结(86)—— Mysql 的 JSON 数据类型正确使用姿势
查看>>
Mysql 学习总结(87)—— Mysql 执行计划(Explain)再总结
查看>>
Mysql 学习总结(88)—— Mysql 官方为什么不推荐用雪花 id 和 uuid 做 MySQL 主键
查看>>
Mysql 学习总结(89)—— Mysql 库表容量统计
查看>>
mysql 实现主从复制/主从同步
查看>>
mysql 审核_审核MySQL数据库上的登录
查看>>
mysql 导入 sql 文件时 ERROR 1046 (3D000) no database selected 错误的解决
查看>>
mysql 导入导出大文件
查看>>
MySQL 导出数据
查看>>
mysql 将null转代为0
查看>>
mysql 常用
查看>>
MySQL 常用列类型
查看>>