You could reason symmetrically, and code e.g.
seg *p = last;
for (int j=0; j < k && p != NULL; j++)
p = p->prev;
I have added the test p != NULL
to avoid an undefined behavior (when the list has fewer than k
elements; on many systems you would get a segmentation violation crash if you omit the test in that case).
Don't forget to enable all warnings and debugging info when compiling (e.g. compile with gcc -Wall -g
) and learn how to use the debugger (e.g. gdb
).
BTW, C++11 is a different language than C99 or C11 (but with some compatibilities) and offer language support (thru its standard library) for linked lists using std::list.