Linked list vs. dynamic array for implementing a stack

There are many tradeoffs involved here and I don’t think that there’s a “correct” answer to this question. If you implement the stack using a linked list with a tail pointer, then the worst-case runtime to push, pop, or peek is O(1). However, each element will have some extra overhead associated with it (namely, the … Read more

Python Logic of ListNode in Leetcode

The short answer to this is that, Python is a pass-by-object-reference language, not pass-by-reference as implied in the question. It means that: result and result_tail are two variables that happen to point at the same value Mutation / Changing of the underlying value (result_tail.next = ListNode(1)) will affect the value shown by result However, assigning … Read more

Rationale behind the container_of macro in linux/list.h

It adds some type checking. With your version, this compiles fine (without warning): struct foo { int bar; }; …. float a; struct foo *var = container_of(&a, foo, bar); With the kernel version, the compiler reports: warning: initialization from incompatible pointer type Good explanation of how the macro works: container_of by Greg Kroah-Hartman.

Best algorithm to test if a linked list has a cycle

Have two pointers iterating through the list; make one iterate through at twice the speed of the other, and compare their positions at each step. Off the top of my head, something like: node* tortoise(begin), * hare(begin); while(hare = hare->next) { if(hare == tortoise) { throw std::logic_error(“There’s a cycle”); } hare = hare->next; if(hare == … Read more

tech