Arrays vs Linked Lists

本文探讨了数组和链表在时间复杂度、内存需求和元素插入方面的差异。数组具有固定大小,插入操作可能涉及整体移动元素,而链表不需要连续内存,但插入操作可能需要遍历。在插入元素时,链表在头部插入时间为O(1),数组在中间或末尾插入通常为O(n)。对于频繁访问元素的场景,数组更优;而链表在内存分配不连续时更有优势。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//网上一个数据结构视频,自己做的笔记

⒈ in terms of time complexity

①array : O(1)

②linked list : O(n)

⒉Requirements

①array

  • fixed size
  • memory may not be available as one large block
  • if you need to access elements in the list all the time

②linked list

  • no unused memory
  • extra memory for pointer variable
  • memory may be available as multiple small blocks

⒊cost of inserting an element in the list
(deleting an element will also have these three scenarios, and the time complexity will also be the same)

(ⅰ) array (also include the possible use of array as dynamic list)
(ⅱ)linked list

three scenarios in insertion:

Ⅰinsert an element at the beginning of the list

(ⅰ) have to shift each element by one position towards the higher index
the time taken will be proportional to the size of the list
O(n)

(ⅱ) creat a new node and adjust the head pointer and the link of this new node
the time taken will not depend upon the size of the list, it will be constant
O(1)

Ⅱinsert an element at the end of an array

(ⅰ) 〔a dynamic list in which we create a new array if it gets filled〕
the time taken will be proportional to n
O(1)

〔if there is space in the array, we just write to the next higher index of the list〕
the time taken will be constant
O(n) (we will have to create a new array and copy all the previous content into new array which will take O(n) time where n is the size of the list)

(ⅱ) traverse the whole list and then create a new node and adjust the links
the time taken will be proportional to n where n is the number of elements in the list
O(n)

Ⅲinsert in the middle of the list at some nth position or may be some ith position

(ⅰ) have to shift elements
For the average case, we may want to insert at the mid position in the array. So, will have to shift n/2 where n is the number of elements in the list
the time taken will be proportional to n in average case
O(n)

(ⅱ) have to traverse till that position and then only we can adjust the links. Even though we will not have any shifting, we will have to traverse till that point
the time taken will be proportional to n
O(n)

⒋which one is easy to use and implement

①An array definitely is a lot easier to use

②Linked list implementation especially in Cor C++ is more prone to errors like segmentation fault and memory leaks. It takes good care to work with linked lists.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值