Actually, fixing that is pretty easy. Yes, you keep a stack of opening tags that you're within, and then whenever you find a closing tag which doesn't match the top of the stack, you need to add the right closing tag and then try again - and again, and again, and again, until everything's back in sync. You also need to handle the end of the document correctly so that you automagically close anything left on the stack.
With a little more trickery (but only a little) you can take account of stuff like <HR> and <BR> not needing to be closed, that only certain tags are legal immediately inside others (eg <TR> is legal inside <TABLE> but <HR> isn't) and so on.
Even if you ignore all those special cases, you'll have a good solution.