Death. It's enough to drive a prince crazy.
In Act V, scene i of Hamlet, after the suicide of Ophelia and before the bloodbath in the final scene, Shakespeare uses the comic relief of the gravediggers to layer his penultimate scene with gothic imagery, morbid jokes, and black humor.
Enotes says it best:
Death, decay, and the futility of life fill the spoken thoughts the Danish prince, and the appearance of Ur-Hamlet's tortured ghost leaves us with cold comfort about the afterlife. Shakespeare skillfully shows vitality being cut short and leading to a gruesome end. Thus, in the graveyard scene that opens Act V, Hamlet holds up the skull of a court jester he knew as a boy, and utters the lines,
Alas, poor Yorick! I knew him, Horatio: a fellow
of infinite jest, of most excellent fancy: he hath
borne me on his back a thousand times; and now,
how abhorred in my imagination it is!
Not only is death pervasive, its occurrence is a product of chance and circumstance. True, Hamlet anticipates his death, while Claudius and, perhaps, Laertes deserve theirs, but Polonius dies by accident as does the Queen, while Ophelia's suicide seems to be beyond her control. Life inevitably yields death and a wormy grave, and its occurrence cannot be foreseen or avoided.
The play begins and ends with death. Hamlet is visited by his dead father in Act I, and here in Act V he visits two dead friends, Yorick and Ophelia. All of their deaths were off-stage as we prepare for the on-stage deaths of Hamlet, Gertrude, Claudius, and Laertes. By the end, the entire cast is laid to rest. This is the realization that Hamlet must accept: the inevitability of death, "the undiscovered country, from whose bourn no traveller returns."
Hamlet is prepared for death prior to this scene. He tells Horatio:
If it be now, 'tis not to come; if it be not to come, it will be now; if it be not now, yet it will come: the readiness is all.
Only until Hamlet is ready to die will he be able to fulfill his duty as heroic avenger.