初級算法之鏈表:反轉鏈表

反轉一個單鏈表。

示例:

輸入: 1->2->3->4->5->NULL 輸出: 5->4->3->2->1->NULL

進階:
你可以迭代或遞歸地反轉鏈表。你能否用兩種方法解決這道題?

方法1:
設置三個指針進行反轉,one和two負責反轉,three負責暫存下一個位置。

ListNode* reverseList(ListNode* head) {
	if (!head || !head->next) return head;
	ListNode *one=head, *two=one->next, *three=two->next;
	head->next = NULL;
	while (two) {
		two->next = one;
		one = two;
		two = three;
		if (three) three = three->next;
	}
	return one;
}

方法2:遞歸
關鍵點在於要記錄尾結點,並且head->next要置空,否則在修改時會出問題
在這裏插入圖片描述

ListNode* reverseList(ListNode* head) {
	if (!head || !head->next) return head;
	ListNode* tail = reverseList(head->next);//記錄尾結點
	head->next->next = head;
	head->next = NULL;
	return tail;
}
發佈了44 篇原創文章 · 獲贊 0 · 訪問量 1283
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章