LeetCode-206-反轉(zhuǎn)鏈表

示例說(shuō)明請(qǐng)見(jiàn)LeetCode官網(wǎng)。
來(lái)源:力扣(LeetCode) ??
鏈接:https://leetcode-cn.com/problems/reverse-linked-list/ ??
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
解法一:迭代
首先,如果head為null或者h(yuǎn)ead只有一個(gè)結(jié)點(diǎn),直接返回head;
否則,聲明2個(gè)參數(shù)first和second分別是head的第一個(gè)和第二個(gè)結(jié)點(diǎn),然后遍歷鏈表:
聲明temp為second的next結(jié)點(diǎn);
將second的next指向first(反轉(zhuǎn));
將first指向second,second指向temp(同時(shí)后移,處理下一個(gè)結(jié)點(diǎn));
當(dāng)second為null時(shí)說(shuō)明遍歷到鏈表的終點(diǎn)了,此時(shí)終止遍歷,first即為反轉(zhuǎn)后新的頭結(jié)點(diǎn)。
【每日寄語(yǔ)】 總有一天,你會(huì)站在最亮的地方,活成自己曾經(jīng)渴望的模樣。
標(biāo)簽: