简体   繁体   中英

What data structure to use to emulate an array in which one can add data in any position?

I want to store a small amount of items( less than 255) which have constant size (ac char )and be able to do the following operations:

  • Append a value to an arbitrary position and have the other items preserve their previous order.

  • Delete an item and have the other items preserve their order(as above).

  • Find the next and previous of an item.

I have tried using an array and making a function to add a value by moving all items after it a place forward.Same thing can happen with deleting, but it is too inefficient.Of course, I do not mind having to use a library, long as it is readily available and free.

  • Array - access: O(1), insert: O(n)
  • Double-linked list - access O(n), previous/next: O(1), insert(*): O(1)
  • RB tree with number of childs stored: O(log n) for all operations.

(*): You need the traverse the list first to get to the position (O(n)).

Note: no, the array is not messy , it's really simple to implement. Also as you can see, depending on the usage, it can be quite efficient.

Based on the number of elements, and your remark to array implementation you should stick to arrays.

You could use a double-linked list for it. However, this won't work if you want to keep the array behaviour (eg accessing elements quickly ( O(1) , for a LL it's O(n) ) by their index)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM