前些日子在翻译论文,检查语法润色啥的。然后跟导师一起修改,前几天终于投了出去,现在可以回到正常的节奏上来了。
先看看题吧
给你一个链表的头节点 head
和一个整数 val
,请你删除链表中所有满足 Node.val == val
的节点,并返回新的头节点 。
示例 1:
输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]
示例 2:
输入:head = [], val = 1
输出:[]
示例 3:
输入:head = [7,7,7,7], val = 7
输出:[]
# 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]:
while head and head.val==val:
head = head.next
pre = head
cur = head
while cur:
if cur.val==val:
pre.next=cur.next
cur=cur.next
else:
pre=cur
cur=cur.next
return head
上述用了双指针,cur指向当前的节点,pre指向当前节点的前一个节点。然后遍历整个链表,通过pre.next=cur.next删除节点。
当然还可以用递归
# 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]:
if not head:
return None
head.next = self.removeElements(head.next,val)
if head.val==val:
return head.next
else:
return head
标签:203,ListNode,cur,val,self,head,next,链表,移除
From: https://blog.51cto.com/u_16123878/7362888