We propose a protocol to generate a Greenberger-Horne-Zeilinger (GHZ) state andWstate by using simple linear elements and quantum nondemolition detectors (QNDs). With the help of cross-Kerr nonlinearity, our protocol can generate the intended states with only one setup, and the probability of getting a W state is greatly increased when compared with previous schemes [Phys. Rev. A 75 (2007) 044301]. Also, our proposed protocol is realizable in experiments.