Leetcode(203):Remove Linked List Elements
2018-01-29 15:37
288 查看
题目: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
分析题目:这个题目要求移除具有某个值的链表中的结点。
思考的流程,判断这个节点是否是满足删除条件的结点,如果是,则将上面的结点的后继变为自己的后继,所以需要记录上一个结点,为了方便,只要判断结点的后继结点,即满足要求。最后再对头结点来进行判断。
代码如下(python版本):
然后看一下大佬们的程序,前几个大佬们的程序自己还是没有搞明白,还是需要继续来看一下大佬实现的思想,学习别人编程的想法,自己训练的多了,也就会用那种思考方式来进行思考了。
大佬的思想与我的应该是差不多的,大佬是在头结点之间加了一个假的头结点,这样可以使得头结点变成了一般的结点,然后统一来进行处理。
Example
Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5
分析题目:这个题目要求移除具有某个值的链表中的结点。
思考的流程,判断这个节点是否是满足删除条件的结点,如果是,则将上面的结点的后继变为自己的后继,所以需要记录上一个结点,为了方便,只要判断结点的后继结点,即满足要求。最后再对头结点来进行判断。
代码如下(python版本):
# 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 head == None: return head node = head while head.next: if head.next.val == val: head.next = head.next.next else: head = head.next if node.val == val: head = node.next else: head = node return head
然后看一下大佬们的程序,前几个大佬们的程序自己还是没有搞明白,还是需要继续来看一下大佬实现的思想,学习别人编程的想法,自己训练的多了,也就会用那种思考方式来进行思考了。
class Solution: # @param {ListNode} head # @param {integer} val # @return {ListNode} def removeElements(self, head, val): dummy = ListNode(-1) dummy.next = head next = dummy while next != None and next.next != None: if next.next.val == val: next.next = next.next.next else: next = next.next return dummy.next
大佬的思想与我的应该是差不多的,大佬是在头结点之间加了一个假的头结点,这样可以使得头结点变成了一般的结点,然后统一来进行处理。
相关文章推荐
- leetcode_c++:链表:Remove Linked List Elements(203)
- leetcode 203 Remove Linked List Elements
- LeetCode 203 Remove Linked List Elements
- Leetcode 203 Remove Linked List Elements 链表
- leetcode-Remove Linked List Elements-203
- leetcode 203 Remove Linked List Elements
- LeetCode 203 Remove Linked List Elements(链表操作)
- LeetCode:203. Remove Linked List Elements
- leetcode[203]:Remove Linked List Elements
- [Leetcode 203, Easy] Remove Linked List Elements
- [C语言][LeetCode][203]Remove Linked List Elements
- Java [Leetcode 203]Remove Linked List Elements
- leetcode 203: Remove Linked List Elements
- Leetcode:203 Remove Linked List Elements(删除链表中的某个元素))
- LeetCode203:Remove Linked List Elements
- 【leetcode 203 Remove Linked List Elements 】
- LeetCode-Easy部分中标签为LinkedList 203 Remove Linked List Elements
- Leetcode 203 Remove Linked List Elements
- <LeetCode OJ> Remove Linked List Elements【203】
- LeetCode笔记:203. Remove Linked List Elements