题目
解答
class LNode():
def __init__(self, val, _next = None):
self.val = val
self.next = _next
class MyLinkedList:
def __init__(self):
"""
Initialize your data structure here.
"""
self.head = None
def get(self, index: int) -> int:
"""
Get the value of the index-th node in the linked list. If the index is invalid, return -1.
"""
k = index
p = self.head
while k > 0 and p is not None:
k -= 1
p = p.next
if p is None: # p是空,就意味没有
return -1
if p is not None:
return p.val
def addAtHead(self, val: int) -> None:
"""
Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
"""
self.head = LNode(val, self.head)
def addAtTail(self, val: int) -> None:
"""
Append a node of value val to the last element of the linked list.
"""
if self.head is None: # 空表
self.addAtHead(val)
return
p = self.head
while p.next is not None:
p = p.next
p.next = LNode(val)
def addAtIndex(self, index: int, val: int) -> None:
"""
Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.
"""
if index <= 0: # index小于,插于表头的情况
self.addAtHead(val)
return
if self.head is None: # 找不到元素的情况
return
p = self.head
k = index - 1
while k > 0 and p is not None:
k -= 1
p = p.next
if p is None: # 说明链表结束
return
if p is not None:
p.next = LNode(val, p.next)
def deleteAtIndex(self, index: int) -> None:
"""
Delete the index-th node in the linked list, if the index is valid.
"""
if self.head is None:
return
if index < 0:
return
if index == 0:
self.head = self.head.next
return
p = self.head
k = index - 1 # 找前一个元素
while p is not None and k > 0:
k -= 1
p = p.next
if p is None:
return
if p is not None and p.next is not None:
p.next = p.next.next
return
# 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)
运行结果
看了提交记录中其他人定义的链表,第一名非常取巧……他包装了Python内置的list类型,直接调用对应的方法,而list的优点在于随机存取和定位元素是 O(1)复杂度的……
易错点分析:
让我头晕好久都是根据index, 实现特定元素的获得,插入或删除。
常规检查:
- index 是否合法(大于等于0)
- 链表是否有对应位置
最让我头晕的是这个循环:
# 这是删除index 位置实现方法的位置
while p is not None and k > 0:
k -= 1
p = p.next
if p is None:
return
if p is not None and p.next is not None:
p.next = p.next.next
return
上面有两个控制变量, 一个是 p 是否为 None, 一个是 k 是否 > 0, 跳出循环有3种可能:
- p 是 None, 到列表尾
- k = 0,到达特定索引位置
- p 是 None 同时 k 到达特定位置
仔细分析可以发现,
-
当 p 是 None的时候,不管 k 等于什么值,该对应操作都是不能实现(非法的)
-
当 p 不是 None的时候, k肯定等于0,于是,我们找到特定位置!