【LeetCode】24. 兩兩交換鏈表中的節點

解題思路

遞歸求解

對於自己寫的遞歸,舉例解釋如下,以1-2-3-4-null爲例

2->1->3->4->null
2->1->4->3->null

參照別人寫的遞歸

2 1->3->4->null 
2 1->4  3->null
2 1->4->3->null
2->1->4->3->null

二者差異在於,我的是每次都會把head和next連接起來,而改進的是,在交換後再進行連接,因此需要保存的量少,變得也就更簡潔了

代碼

自己寫的遞歸

class Solution {
public:
	ListNode* swapPairs(ListNode* head) {
		//空節點或者只剩一個節點
		if (head == nullptr || head->next == nullptr) return head;
		else
		{
			//交換列表中的前兩個節點head和head.next
			ListNode* tempFirst = head;
			ListNode* tempHead = head->next;//交換後新的頭節點爲head.next
			ListNode* tempSecond = head->next->next;
			head->next->next = tempFirst;
			head->next = tempSecond;
			head = tempHead;//更新一下交換後的頭節點
			//將交換後子列表的返回頭和head.next.next相連
			head->next->next = swapPairs(head->next->next);
		}
		return head;
	}
};

參考別人寫的遞歸

//參考別人後更簡化的寫法
class Solution {
public:
	ListNode* swapPairs(ListNode* head) {
		
		//空節點或者只剩一個節點
		if (head == nullptr || head->next == nullptr) return head;
		ListNode* next = head->next;
        //將子列表的返回節點與head.next相連,形成新的鏈表
		head->next = swapPairs(next->next);
		//將交換後的next指向head,將next和head連接起來
		next->next = head;
		return next;
	}
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章