This is an excellent question, and I believe the answer really speaks to Shakespeare's crafty planning.
Hamlet has to die at the end of the play because of his impulsive killing of Polonius. There is a cycle of sons seeking revenge for their father's deaths throughout the play: Young Fortinbras and Old Fortinbras, Young Hamlet and Old Hamlet, and, finally, Laertes and Polonius. Hamlet does get his revenge against Claudius, and Laertes deserves to get his as well. When he stabs Hamlet with the poisoned sword, he is delivering Hamlet his final reward, and Hamlet understands and accepts this.
Claudius is poisoned twice before he dies. He gets what is coming to him when he is stabbed by Hamlet at the end of the play with the sword that he, himself, poisoned, intending for it to be used on Hamlet. Hamlet also pours poison into Claudius's mouth. This is the perfect deadly reward for him, since, at this point in the play, he is responsible for killing Old Hamlet and, now, Gertrude, both with poison. This also marks the end of Hamlet's ongoing internal conflict, as he has finally carried out his act of revenge.
Gertrude, in her final moments, realizes that she has been poisoned by the drink concocted by Claudius, her new husband and late husband's brother. In this instant, she realizes that Hamlet's assessment of Claudius being a callous murderer has been correct all along. She dies realizing that she has made a fatal error in trusting Claudius and that she has, in fact, "much offended" her late husband, Hamlet's father, by marrying his murderer.
Act V of the play ends perfectly because of this. The only truly innocent character left is Horatio, who lives on to tell the story.