leetcode刷題.143. 重排連結串列.每日打卡

paradox_1_0發表於2020-10-25

程式碼:

class Solution {
public:
    /* 連結串列反轉 */
 	ListNode* reverse(ListNode* head) {

		if (nullptr == head)
			return head;

		ListNode* p1 = nullptr, * p2 = head;
		ListNode* p3 = p2->next;

		while (nullptr != p3) {
			p2->next = p1;
			p1 = p2;
			p2 = p3;
			p3 = p3->next;
		}
		p2->next = p1;
		return p2;
	}

    /* 兩個連結串列交叉合併 */
	void merge(ListNode* p1, ListNode* p2) {

		if (nullptr == p2)
			return;

		ListNode* pp1 = p1, * pp2 = p2;
		ListNode* pp3 = pp1->next;
		ListNode* pp4 = pp2->next;
		while (nullptr != pp1 && nullptr != pp2) {
			pp1->next = pp2;
			pp2->next = pp3;
			pp1 = pp3;
			pp2 = pp4;
			if(nullptr != pp3) pp3 = pp3->next;
			if(nullptr != pp4) pp4 = pp4->next;
		}
	}

	void reorderList(ListNode* head) {

		if (nullptr == head)
			return;

		ListNode* p1 = head, * p2 = head;
		while (nullptr != p2) {
			p2 = p2->next;
			if (nullptr != p2) {
				p2 = p2->next;
				p1 = p1->next;
			}
		}

		if (nullptr == p1) {
			return;
		}

		p2 = p1->next;
		p1->next = nullptr;

		/* 對後半段連結串列進行反轉,p2 */
		ListNode* last = reverse(p2);

		/* 交叉合併 */
		merge(head, last);
	}
};

 

相關文章