题目描述:
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的元素。
解题思路:
使用“哑节点”记录链表头部
循环遍历链表时使用pre, cur记录上一个元素和当前元素
Python代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param {ListNode} head
# @param {integer} val
# @return {ListNode}
def removeElements(self, head, val):
dummy = ListNode(0)
dummy.next = head
pre, cur = dummy, head
while cur:
if cur.val == val:
pre.next = cur.next
else:
pre = cur
cur = cur.next
return dummy.next
上面代码中的变量个数可以进一步化简,只需要使用一个变量cur记录当前节点即可。
Python代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param {ListNode} head
# @param {integer} val
# @return {ListNode}
def removeElements(self, head, val):
dummy = ListNode(0)
dummy.next = head
cur = dummy
while cur and cur.next:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
return dummy.next
另外分享一个LeetCode Discuss中看到的Java版递归解法,非常简洁。
Java代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
if (head == null) return null;
head.next = removeElements(head.next, val);
return head.val == val ? head.next : head;
}
}
Python采用递归法解题会返回Runtime Error,可能和栈溢出有关。
本文链接:http://bookshadow.com/weblog/2015/04/24/leetcode-remove-linked-list-elements/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。