This paper is concerned with a gait generation framework for legged robots based on iterative learning control (ILC) of Hamiltonian systems. This method allows one to obtain solutions to a class of optimal control problems by iteration of laboratory experiments and, furthermore, precise knowledge of the plant model is not required for it by taking advantage of a symmetric property of Hamiltonian systems. Generally in walking motion, there are discontinuous state transitions caused by collision between the foot and the ground. The proposed framework can also deal with such state transitions without using the parameters of the transition model by combining ILC method and the least-squares. It is applied to a compass-like biped robot to generate optimal gait on the level ground. Some numerical examples demonstrate the effectiveness of the proposed method.