Is it possible to insert an unsigned long
into a linked list ordered from smallest to largest without dynamic memory, using malloc
or free
?
Asked
Active
Viewed 1,375 times
-3

Ṃųỻịgǻňạcểơửṩ
- 2,517
- 8
- 22
- 33

Priyank Pandya
- 23
- 6
-
2You can use an array to store integers in the list. – Vlad from Moscow May 08 '15 at 06:04
-
Can you explain it with an example? Sorry I am new to C – Priyank Pandya May 08 '15 at 06:15
-
All you need is to write a function that inserts integers in an array in the given order. – Vlad from Moscow May 08 '15 at 06:30
-
1@VladfromMoscow But that wouldn't make it "a linked list", would it? – unwind May 08 '15 at 06:34
-
possible duplicate of [Linked Lists in C without malloc](http://stackoverflow.com/questions/3856317/linked-lists-in-c-without-malloc) – WedaPashi May 08 '15 at 06:42
-
1@unwind It will be a linked list. The array is simply is an allocator. – Vlad from Moscow May 08 '15 at 06:44
-
@VladfromMoscow: No it won't be. – WedaPashi May 08 '15 at 06:53
-
@WedaPashi You can use different allocators with the same data structure. And an array is one of allocators. See also the answer to the question. – Vlad from Moscow May 08 '15 at 07:01
-
@VladfromMoscow Sure, you can use an array to get the storage, but that's not what your original comment sounded like, which is why I questioned it. – unwind May 08 '15 at 07:07
-
@VladfromMoscow: Blam! With all due respect to you, (but) Don't be surprised if I take that too personal and offensive. (BTW, its *qualification*, I assume a good programmer is good with keyboards as well) – WedaPashi May 08 '15 at 07:18
1 Answers
4
You can pre-allocate a bunch of list entries in the form of an array, then pick entries from that array when you do an insert. This is of course only possible if the array is either global, or at otherwise kept in scope for the duration of the insertion operation.
Something like:
struct integerNode {
int value;
struct integerNode *next;
};
struct integerNode nodes[100]; /* adjust for your number of integers */
The next step would be to use a trivial for
loop to link the items in nodes
together, forming a linked list of free items. Then write a function that de-links a node from the free list and links it into another list, while inserting the number.

unwind
- 391,730
- 64
- 469
- 606