//网上一个数据结构视频,自己做的笔记
⒈ 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.