r/cprogramming • u/souls-syntax • Mar 11 '26
Optimizing linked list to have O(1) time complexity for appending at tail.
So came across a nice trick where you hide some metadata before the actual DS and then while doing operations you just retrieve the meta data and do task more efficiently .
So i defined a struct at the start of linkedlist and have count and the pointer to last node stored there and whenever I needed to append I just got the last node pointer from there and just update it.
So i guess a small optimization.
But I really enjoyed this putting hidden data and working with it.
I think it's super cool, do you guys also find it cool ?
Here is the data structure and initializing function I implemented.
\
typedef struct Header {
int count;
struct Node* LastElement;
} Header;
typedef struct Node {
int value;
struct Node* next;
} Node;
Node* createFirstNode(int value) {
Header* header = (Header*)malloc(sizeof(Node) + sizeof(Header));
if(header == NULL) {
printf("Error: Memory allocation failed");
exit(1);
}
header->count = 1;
Node* newNode = (Node *)(header + 1);
newNode->value = value;
newNode->next = NULL;
header->LastElement = (Node *)(header + 1);
return newNode;
}
\
It's probably not the best way or even standard way but when I started implementing it i didn't really think much further ahead and just kind of did it and when complications occurred I just coped harder.
Don't look too hard in how it will just break if someone passed mid node or how i should have implemented opaque struct or whatever.
Cool trick right eh eh eh!!
15
u/dkopgerpgdolfg Mar 11 '26
Some technical suggestions / problems:
count (but not value) should be size_t
Malloc size ignores possible padding.
If your use of the malloc'ed memory violates strict aliasing is an unsolved question to the standard commitee, possibly yes. (For the space of the header struct, it's clear that the first use marks it as header and doesn't allow wrongly typed pointer access anymore. But it's not clear from the standard if this applies to the rest of the malloced memory too. Defect report unresolved for about 20 years :/)
And with your offsetting of the pointer, depending on the further use you get into memory scope / provenance trouble, because it might not be allowed to access the "hidden" memory before the pointer later.
8
u/[deleted] Mar 11 '26
Why do you want to "hide" anything? Who are you hiding it from? 🧐
6
u/not-just-yeti Mar 11 '26
Nice! This same trick (keeping an extra pointer to the last node) is also used when making a doubly-linked list.
Minor note: I wouldn't
mallocthe first node as part of the header. For starters, what if somebody wants to create a list, but ends up later never putting anything into it? Or, if they remove the only thing in the list? Or worst of all: if they remove the first element of the list. These situations can all be handled, but you'll have lots of extra code to cope with the "first node is allocated differently from all other nodes". I'd suggest havingHeaders hold header data, andNodes hold each node data, and don't try to mush them together.Also, pro-tip (for doubly-linked lists, and usable here too): keep two
Header-ish nodes — one for each end. This makes your code for handling the empty list much simpler.1
u/souls-syntax Mar 11 '26
Github link : https://github.com/souls-syntax/C-STL/tree/main/LinkedList
4
u/sreekotay Mar 11 '26
Lookup circular linked list. You can do this without an extra special node.
Then you always use the Last link as the “list”
The first link the head->next
1
u/SimoneMicu Mar 11 '26
It should be UB. Most of the time tou are exposing data and libraries to educated programmers because they know how to compile the given library or how to download and link it, most of the time that programmer is you. A respectful idea is to not store hidden data when not required (a good case of hidden data or metadata is in a pool allocator where you want to store info like if the block is allocated and the next pool block if exist, something like
struct { uintptr next; size_t size; unsigned char mem[]; };and pass the reference to the flexible array member) and in this single linked list keeping reference to first and last pointer so it will be easier to append and easy to reach1
u/Ok-Selection-2227 Mar 12 '26
The trick you're trying to use is useful when you deal with arrays, because then you can still use the [ ] operator to access elements of the array. But here it is totally useless.
3
u/WittyStick Mar 12 '26 edited Mar 12 '26
There's no point in "hiding" the structure - just make it explicit and use
offsetof.This doesn't require magic number offsets and UB - you can add or remove stuff from the header and it will still work as expected.
2
u/zhivago Mar 12 '26
What you're really doing here is building a queue.
There's another approach to this which you might find interesting.
You take a pair of linked lists -- one starting at the head and going forward, and one starting at the tail and going backward.
When you exhaust the forward list, you replace it with the reversed tail list.
This has amortized O(1) time complexity and is also suitable for immutable data structures, although it is a more expensive O(1). :)
This means that you can have multiple queues sharing substructure, which is occasionally useful.
2
u/al2o3cr Mar 13 '26
Be careful with early-returns from functions: it's easy to leak memory.
For instance:
https://github.com/souls-syntax/C-STL/blob/7b2876e2ed6b209f5ba301a8999f7cba7f1a69c3/LinkedList/linkedlist.c#L40-L44
If
appendis passed bad input, the memory allocated fornewNodewill never be freed1
u/Abject-Hat-4633 Mar 13 '26
similar to the stb library array implementation i would say , and tsoding also explain about this 'data_shadowing in c ' video
0
u/[deleted] Mar 11 '26
[deleted] — view deleted comment