LeetCode 203. 移除链表元素
链表基础概念题,也可以用递归做,不过我们把递归的思想放在更能体现它的LeetCode 206.反转链表
# 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 head
dummy = ListNode()
dummy.next = head
p = dummy
while p and p.next:
if p.next.val == val:
p.next = p.next.next
else:
p = p.next
return dummy.next
LeetCode 707.设计链表
同样是基础的链表操作,注意定义一个ListNode类
class ListNode:
def __init__(self, val = 0, next = None):
self.val = val
self.next = next
LeetCode 206.反转链表
递归
# 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]:
if not head or not head.next:
return head
new_head = self.reverseList(head.next)
head.next.next = head
head.next = None
return new_head
标签:head,val,self,随想录,next,链表,LeetCode
From: https://www.cnblogs.com/li508q/p/18417691