这题我采用了另一个思路,转化为list,然后删除元素之后再按照list转回来。代码如下:
# 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
"""
b = []
if head == None:
return None
while head != None:
b.append(head.val)
head = head.next
for i in range(len(b))[::-1]:
if b[i] == val:
del b[i]
print b
c = ListNode(0)
a = c
for i in b:
a.next = ListNode(i)
a = a.next
return c.next
时间上耗费倒是挺多的,先尝试一下.
从另外一道题上得到了启发,于是修改了一下:
# 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
"""
c = head
if c == None:
return None
while c!= None:
if c.next != None:
if c.val == val:
c.val = c.next.val
c.next = c.next.next
else:
c = c.next
else:
if c.val != val:
break
else:
slow = head
fast = head
if slow.next == None:
return None
slow = slow.next
while slow.next != None:
slow = slow.next
fast = fast.next
fast.next = fast.next.next
break
return head