When endstop is hit, stop making steps but count how many "virtual steps" are made. Then when moving in the opposite direction decrement the counter and start stepping when it hits zero.
And when next recalculating update the current position with the virtual steps
Kliments idea
if(!endstop)step;else(++counter);
if(counter)counter--; else step;
Kliments idea if(!endstop)step;else(++counter); if(counter)counter--; else step;