标签:
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
通过判断p.next的值是否相等于提供的值确定p的下一个node可以省一个指针。
var removeElements = function(head, val) { if(!head) return null var dummy = new ListNode() dummy.next = head var p = dummy while(p.next) if(p.next.val===val) p.next = p.next.next else p = p.next return dummy.next };
也可以使用双指针previous,current。每次判断current是否相等于提供的值然后确定previous的下一个node。
def remove_elements(head, val) return if not head dummy = ListNode.new(0) dummy.next = head previous = dummy current = head while current if current.val == val previous.next = current.next else previous = current end current = current.next end dummy.next end
Leetcode 203 Remove Linked List Elements
标签:
原文地址:http://www.cnblogs.com/lilixu/p/4603578.html