# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
dummy=ListNode(-1,head)
ans=dummy
while dummy.next:
if dummy.next.val!=val:
dummy=dummy.next
else:
dummy.next=dummy.next.next
return ans.next
#通过循环完成,当链表中的元素等于规定的值元素时,将该元素的next指针指向next.next也就是直接跳过这个元素,最后返回ans.next,相当于整个元素链表。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
# 按照饲养员解法超出时间限制
# dummy=ListNode(0)
# dummy.next=head
# while head is not None and head.next is not None:
# dnext=dummy.next
# hnext=head.next
# dummy.next=hnext
# head.next==hnext.next
# hnext.next=dnext
# return dummy.next
#参考解法 双指针解法
pre=None
cur=head
while cur is not None:
temp=cur.next
cur.next=pre
# 更新迭代
pre=cur
cur=temp
return pre