Is a Linked-List implementation without using pointers possible or not?

前端 未结 14 1550
再見小時候
再見小時候 2020-12-01 07:57

My question is very simple, can one using C++, implement a link-list data structure without using pointers (next nodes)? To further qualify my question, I\'m mean can one cr

14条回答
  •  隐瞒了意图╮
    2020-12-01 08:44

    Yes you can, it is not necessary to use pointers for a link list. It is possible to link a list without using pointers. You can statically allocate an array for the nodes, and instead of using next and previous pointer, you can just use indexes. You can do that to save some memory, if your link list is not greater than 255 for example, you can use 'unsigned char' as index (referencing C), and save 6 bytes for next and previous indications.

    You may need this kind of array in embedded programming, since memory limitations can be troublesome sometimes.

    Also keep in mind that your link list nodes will not necessary be contiguous in the memory.

    Let's say your link list will have 60000 nodes. Allocating a free node from the array using a linear search should be inefficient. Instead, you can just keep the next free node index everytime:

    Just initialize your array as each next index shows the current array index + 1, and firstEmptyIndex = 0.

    When allocating a free node from the array, grab the firstEmptyIndex node, update the firstEmptyIndex as next index of the current array index (do not forget to update the next index as Null or empty or whatever after this).

    When deallocating, update the next index of the deallocating node as firstEmptyIndex, then do firstEmptyIndex = deallocating node index.

    In this way you create yourself a shortcut for allocating free nodes from the array.

提交回复
热议问题