203. Remove Linked List Elements [easy] (Python)
2016-06-18 16:30
555 查看
题目链接
https://leetcode.com/problems/remove-linked-list-elements/题目原文
Remove all elements from a linked list of integers that have value val.Example
Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5
题目翻译
删除单链表中值为给定的val的节点。比如:给定链表 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6 和值 val = 6 ,返回 1 –> 2 –> 3 –> 4 –> 5 。思路方法
思路一
遍历所有节点,同时保留每个节点的上一个节点,当遇到节点值是val时,删除该节点。为了方便操作,定义了一个伪头节点。代码
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeElements(self, head, val): """ :type head: ListNode :type val: int :rtype: ListNode """ new_head = pre = ListNode(0) pre.next = head while head: if head.val == val: pre.next = head.next else: pre = pre.next head = head.next return new_head.next
思路二
题目没有要求不改变节点的值,那么可以定义快慢两个指针,在快指针遍历链表的时候,将不等于val值的节点的值赋给慢指针指向的节点。代码
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeElements(self, head, val): """ :type head: ListNode :type val: int :rtype: ListNode """ new_head = ListNode(0) new_head.next = head slow, fast = new_head, head while fast: if fast.val != val: slow.next.val = fast.val slow = slow.next fast = fast.next slow.next = None return new_head.next
说明
上面的解法都用到了dummy node,其实可以先将从头部开始的val值得节点去除,这样就不需要额外的节点了。
另外,这道题可以用递归来做,代码很简单但无法AC。。。不过用C语言写同样的代码可以AC,所以下面写一下算是提供思路,仅供参考吧。
代码(递归,未AC)
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeElements(self, head, val): """ :type head: ListNode :type val: int :rtype: ListNode """ if not head: return head head.next = self.removeElements(head.next, val) return head if head.val != val else head.next
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:/article/11857871.html
相关文章推荐
- Python Collections Counter
- python 跨语言数据交互、json、pickle(序列化)、urllib、requests(爬虫模块)、XML。
- Python中找list中最大n个数的包heapq.nlargest
- 257. Binary Tree Paths [easy] (Python)
- 双色球 python
- 搞不懂 numpy.sum 请过来
- 记录
- python用openpyxl操作excel
- python用openpyxl操作excel
- 第四章 Python外壳:代码结构
- Python中使用装饰器来优化尾递归的示例
- sublime 3 注册码+PYTHON 环境配置+pylint插件path问题+package control找不到packages解决方法。
- 决策树
- 以图搜图(一):Python实现dHash算法(转)
- Python爬虫入门之request函数定制
- Python爬虫入门之request函数定制
- Python爬虫入门之request函数定制
- Python爬虫入门之request函数定制
- Python爬虫入门之request函数定制
- Python爬虫入门之request函数定制