203.移除链表元素
题目链接:https://leetcode.cn/problems/remove-linked-list-elements/
文章讲解:代码随想录
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
# Remove from the beginning if head has the value val
dummy_head = ListNode(next=head)
p = dummy_head
while p.next:
if p.next.val == val:
p.next = p.next.next
else:
p = p.next
return dummy_head.next
主要学习一下用伪节点的写法
注意要返回的dummy.next,不是p.next;熟悉python语言的链表表示和判断非空的方式
707. 设计链表
题目链接:https://leetcode.cn/problems/remove-linked-list-elements/description/
文章讲解:代码随想录
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class MyLinkedList:
def __init__(self):
self.dummy_head = ListNode()
self.size = 0
def get(self, index: int) -> int:
if index < 0 or index >= self.size:
return -1
p = self.dummy_head.next
for i in range(index):
p = p.next
return p.val
def addAtHead(self, val: int) -> None:
self.dummy_head.next = ListNode(val, self.dummy_head.next)
self.size += 1
def addAtTail(self, val: int) -> None:
p = self.dummy_head
while p.next:
p = p.next
p.next = ListNode(val)
self.size += 1
def addAtIndex(self, index: int, val: int) -> None:
if index < 0 or index > self.size:
return
p = self.dummy_head
for i in range(index):
p = p.next
p.next = ListNode(val, p.next)
self.size += 1
def deleteAtIndex(self, index: int) -> None:
if index < 0 or index >= self.size:
return
p = self.dummy_head
for i in range(index):
p = p.next
p.next = p.next.next
self.size -= 1
# Your MyLinkedList object will be instantiated and called as such:
# obj = MyLinkedList()
# param_1 = obj.get(index)
# obj.addAtHead(val)
# obj.addAtTail(val)
# obj.addAtIndex(index,val)
# obj.deleteAtIndex(index)
注意对index输入的判别
206.反转链表
题目链接:https://leetcode.cn/problems/reverse-linked-list/description/
文章讲解:代码随想录
视频讲解:帮你拿下反转链表 | LeetCode:206.反转链表 | 双指针法 | 递归法_哔哩哔哩_bilibili
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
cur = head
pre = None
while cur:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
return pre
第一次有点路径依赖了,还是想写伪头节点,后来发现并不合适
然后递归的做法还没有太理解...