A new algorithm for inferring the evolution of within-host viral sequences is presented. A sequential-linking approach is developed so that a longitudinal phylogenetic tree can be reconstructed from sequential molecular data that are obtained at different time points from the same host. The algorithm employs a codon-based model, which uses a Markov process to describe substitutions between codons, to calculate nonsynonymous and synonymous substitution rates and to distinguish positive selection and neutral evolution. The algorithm is applied to a data set of the V3 region of the HIV-1 envelope genes sequenced at different years after the infection of a single patient. The results suggest that this algorithm may provide a more realistic description of viral evolution than traditional evolutionary models, because it accounts for both neutral and adaptive evolution, and reconstructs a longitudinal phylogenetic tree that describes the dynamic process of viral evolution.