Scholars have debated this question for hundreds of years, but the general consensus seems to be that Hamlet is not mad, but terribly conflicted. This confliction often looks like madness, as when he verbally abuses Ophelia, or has a meaningful conversation with Yorick's skull. And, of course, speaking to the Ghost of his father.
Hamlet's conflicts are understandable. His father has been murdered by his uncle, his mother betrays his father's memory by marrying the evil Claudius; Hamlet's friends turn out to be "sponges" for the false king, and he accidentally kills his girlfriend's father. Despite all this evidence, Hamlet has to bring himself to act out the revenge he knows is necessary, not an easy thing to do.