Trains that keep running for a long time usually have restrooms, while trains that makes stops less than every ten minutes or so don't. But there are always restrooms inside the station. If the restroom is outside the ticket gate, you can ask the staff to let you out without surrendering your ticket.