Thirty-one years after Stalinists hanged him for treason and dumped his body into an unmarked grave, the Communist prime minister who defied Moscow during the Hungarian revolution received the hero`s funeral Friday that freedom fighters always knew he deserved.

More than 100,000 ordinary Hungarians flocked to Budapest`s vast Heroes`

Square to pay belated homage to Imre Nagy. He was executed on June 16, 1958, after a secret trial on trumped-up charges.

The somberly dressed crowd-many carrying armloads of flowers or waving old national flags with Hungary`s Communist Party emblem cut out from the center to leave a gaping hole-heard funeral speakers condemn the Soviet invasion that crushed the revolution of 1956 and call for the total ouster of Soviet troops still stationed in the country.

Later, hundreds of family members assembled at Plot 301 in Budapest`s general cemetery to rebury Nagy and four of his closest associates in an emotional ceremony that never would have taken place before Soviet President Mikhail Gorbachev began preaching reform of the communist world. That the funeral was permitted, let alone broadcast to the entire nation, was a monument to Hungary`s accelerating program of glasnost and perestroika.

''People who believe in democracy have come today to remember your death,'' historian Tibor Meray said at a graveside eulogy to Nagy, who announced Hungary`s withdrawal from the Soviet-led Warsaw Pact at the height of the uprising.

''You were the one who opened the windows to the spirit of freedom. All those who were punished in the past 40 years came to your grave today and thank you that they can once again lift their heads.''

Reburied with Nagy were his closest government associates: Defense Minister Pal Maleter, Cabinet leader Jozsef Szilagyi, Minister of State Geza Losonczy and Nagy`s secretary, Miklos Gimes. All five had been vilified for three decades, until Nagy`s successor as Hungarian leader, Janos Kadar, was ousted from power in May, 1988.

Only last June, on the 30th anniversary of Nagy`s execution, family and friends were given grudging permission to erect a tiny wooden marker on the desolate cemetery plot where the victims had been hastily buried.

But police beat many in the crowd after they tried to set up a public memorial in the center of town.

Since then, however, the party has given up its traditional pretense that Nagy was a counterrevolutionary bent on destroying communism and instead has proclaimed him and his associates guiltless martyrs and the victims of illegal executions.

Four government leaders attended the memorial service on the square:

Prime Minister Miklos Nemeth, Deputy Prime Minister Peter Medgyessy, reformist Minister of State Imre Pozsgay and Parliament Speaker Matyas Szuros. They did not speak but stood briefly in a rotating honor guard posted around each of the six coffins, the extra one empty and meant to honor every Hungarian who died in the uprising.

For four hours, people from all parts of the country-some in wheelchairs, some using canes, one rolled in on a hospital gurney-filed past the coffins to lay what soon became six mountains of flowers. At half past noon church bells rang out across the country as the nation observed a moment of silence. Workers put down their tools and many motorists stopped their cars in the middle of normally busy thoroughfares.

The crowds were somber and generally silent throughout the public ceremonies, and many people cried as they filed past the coffins. Nagy`s casket was covered by a blanket of red carnations and bore a simple black ribbon that read, ''With the nation, for the nation, until death.''

The private funeral at the cemetery focused largely on personal attributes, but the speakers in Heroes` Square appeared to shock many in the crowd with their strongly worded denunciations of the Communist Party, the Soviet leadership at the time of the revolution and the continued Soviet presence in Hungary. Since the nation saw thousands die in the revolution and its bloody aftermath, any public utterances of a political nature have been avoided at all costs.

The crowd was largely silent as mourners listened to the survivors of the revolution denounce the past.

''We wouldn`t be in such a situation if the Soviet Union hadn`t crushed our revolution in such a bloody way,'' said Imre Mecs, a member of the Committee for Historical Justice that has fought, along with family members, for the rehabilitation of all the victims of the uprising.

''They committed not only a sin but a great historical mistake when they brutally prevented the Hungarian nation from going its own way.''

The crowd also failed to respond to a forceful address by Sandor Racz, chairman of the Budapest worker councils that seized power in factories during the revolution. Racz said the Communist Party was an obstacle to Hungary regaining its freedom.

''It clings to power,'' Racz said of the party. ''It`s obvious to anybody that what they did not do in 43 years cannot be done now.''

But Viktor Orban, the feisty leader of the youth group Fidesz, roused the crowd from its silence with an address interrupted seven times by loud applause. And the crowd broke into cheers and began flashing victory signs when Orban addressed the still touchy issue of the Soviet troop presence in Hungary.

''If we can trust our souls and strength we can put an end to the Communist dictatorship,'' Orban said.

''If we are determined enough we can force the ruling party to submit itself to free elections, and if we do not lose sight of the ideas of 1956 we will be able to elect a government that will start immediate negotiations about the prompt withdrawal of Russian troops.''

Orban said Hungarians would never again ''accept the empty promises of Communist leaders-our goal is that the ruling party, even if it wished, would be unable to use force against us. This is the only way to avoid new coffins, new burials as today`s.''

Hundreds of people lined the motorcade route to the cemetery, standing at attention as the hearses carried the flower-decked coffins back to spot where they have lain unmarked since 1958. Since the bodies were exhumed in late March, the authorities have been working round-the-clock to make the site look like a normal cemetery plot.