时间复杂度
- 访问Access — O(N)
- 搜索Search — O(N)
- 插入Insert — O(1)
- 删除Delete — O(1)
特点
- 写的快
- 读很慢
- 读少写多
常用操作
-
创建链表
linkedlist = deque()
– -
添加元素
linkedlist.append()
(添加的元素)
O(1)
–
linkedlist.insert(2, 99)
(插入的索引,插入的元素)
O(N)
– -
访问元素
element = linkedlist[2]
O(N)
– -
查找元素
index = linkedlist.index(99)
(查找的元素)
返回索引
O(N)
– -
更新元素
linkedlist[2] = 88
O(N)
– -
删除元素
linkedlist.remove(88)
(删除的元素)
O(N)
–
del linkedlist[2]
(删除的索引)
O(N)
– -
链表的长度
length = len(linkdlist)
O(1)
练习题
- 203 . 移除链表元素
class Solution:
# One Pass
# N is the size of head linkedlist
# Time Complexity: O(N)
# Space Complexity: O(1)
def removeElements(self, head: ListNode, val: int) -> ListNode:
dummy = ListNode(0)
dummy.next = head
prev = dummy
while head is not None:
if head.val == val:
prev.next = head.next
else:
prev = prev.next
head = head.next
return dummy.next
- 206 . 反转链表
class Solution:
# Iteration
# N is the size of head linkedlist
# Time Complexity: O(N)
# Space Complexity: O(1)
def reverseList(self, head: ListNode) -> 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
学习视频来源B站—爱学习的饲养员—手把手带你刷Leetcode力扣