合併兩個有序鏈表(三種方法)---C++實現

方法一:若要求不能對原始鏈表更改,則必須使用額外空間

//使用額外空間來合併鏈表 不對原始鏈表做改變
node* mergeTwoLinkListWithExtraPlace(node *head1, node *head2) {
	/*先創建一個頭結點 這裏用任意的整數都可以 不一定用0 之後返回newHead->next
	即可 該方法在很多時候都可以起到簡化代碼的作用 值得借鑑*/
	node *newHead = new node(0);
	node *tail = newHead; //記錄尾節點 方便尾插法
	node *p = head1;
	node *q = head2;
	while (p && q) {
		if (p->data < q->data) {
			node *r = new node(p->data);
			p = p->next;
			tail->next = r;
		}
		else {
			node *r = new node(q->data);
			q = q->next;
			tail->next = r;
		}
		tail = tail->next;
	}
	//如果有一個鏈表到達了尾部
	while (p) {
		node *r = new node(p->data);
		tail->next = r;
		tail = tail->next;
		p = p->next;
	}
	while (q) {
		node *r = new node(q->data);
		tail->next = r;
		tail = tail->next;
		q = q->next;
	}
	return newHead->next; //這裏頭結點直接丟棄 保證完整性 可以釋放頭結點 如下
	/*node *r = newHead;
	newHead = newHead->next;
	delete r;
	r = nullptr;
	return newHead;*/
}

方法二:更改原始鏈表 主要利用循環實現

//非遞歸的方式 也成迭代法
node* mergeTwoSortedLinkListWithoutRecursion(node* head1, node* head2) {
	node* newHead = new node(0); //先創建一個鏈表頭結點 返回的時候返回頭結點下一個結點即可
	node *p = head1;
	node *q = head2;
	node* tail = newHead; //這個結點用來記錄合併後鏈表的尾節點 方便進行尾插法
	while (p && q) {
		if (p->data < q->data) {
			tail->next = p;
			p = p->next;
		}
		else {
			tail->next = q;
			q = q->next;
		}
		tail = tail->next;
	}
	//以下情況是有一個鏈表走到了尾部
	if (p) {
		tail->next = p;
	}
	if (q) {
		tail->next = q;
	}
	return newHead->next;  //這裏頭結點最好釋放一下 如下
	/*node *r = newHead;
	newHead = newHead->next;
	delete r;
	r = nullptr;
	return newHead;*/
}

方法三:一般絕大多數鏈表和樹的題目都可以用遞歸實現,注意遞歸出口條件

node* mergeTwoSortedLinkListWithRecursion(node* head1, node* head2) {
	//如果head1 和 head2有一個爲空 則直接返回另一個
	if (!head1) {
		return head2;
	}
	if (!head2) {
		return head1;
	}
	//遞歸可以理解爲之後的情況都處理好了 只需要解決好當前這步就行了
	if (head1->data < head2->data) {
		head1->next = mergeTwoSortedLinkListWithRecursion(head1->next, head2);
		return head1;
	}
	else {
		head2->next = mergeTwoSortedLinkListWithRecursion(head1, head2->next);
		return head2;
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章