【手把手带你刷Leetcode力扣】3.数据结构 - 链表

时间复杂度

  • 访问Access — O(N)
  • 搜索Search — O(N)
  • 插入Insert — O(1)
  • 删除Delete — O(1)

特点

  • 写的快
  • 读很慢
  • 读少写多

常用操作

  1. 创建链表
    linkedlist = deque()

  2. 添加元素
    linkedlist.append()
    (添加的元素)
    O(1)

    linkedlist.insert(2, 99)
    (插入的索引,插入的元素)
    O(N)

  3. 访问元素
    element = linkedlist[2]
    O(N)

  4. 查找元素
    index = linkedlist.index(99)
    (查找的元素)
    返回索引
    O(N)

  5. 更新元素
    linkedlist[2] = 88
    O(N)

  6. 删除元素
    linkedlist.remove(88)
    (删除的元素)
    O(N)

    del linkedlist[2]
    (删除的索引)
    O(N)

  7. 链表的长度
    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力扣

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值