关闭

合并两递增链表

81人阅读 评论(0) 收藏 举报
分类:

一、循环实现

#include <iostream>

using namespace std;

struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
		val(x), next(NULL) {
	}
};

class Solution {
public:
	ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
		ListNode *Head = NULL;
		//输入合法性检测
		if (pHead1 == NULL){
			return pHead2;
		}
		if (pHead2 == NULL) {
			return pHead1;
		}
		//判断合并链表头节点是从哪个节点开始
		if (pHead1->val <= pHead2->val) {
			Head = pHead1;
		} 
		else {
			Head = pHead2;
		}
		ListNode *preHead = NULL, *nextHead = NULL;
		while (pHead1 != NULL && pHead2 != NULL) {
			if (pHead1->val <= pHead2->val) {
				while (pHead1 != NULL && pHead1->val <= pHead2->val) {
					preHead = pHead1;//临时保存链表1遍历的上一个节点
					pHead1 = pHead1->next;
				}
				preHead->next = pHead2;//链表1遍历的上一个节点后继链表2当前节点(插入节点开始)
				nextHead = pHead2->next;//临时保存链表2当前节点的下一个节点
				pHead2->next = pHead1;//链表2当前节点后继链表1当前节点(插入节点完成)
				pHead1 = preHead->next;//链表1当前节点退回到刚插入进去的节点
				pHead2 = nextHead;//链表2当前节点后移
			}
			else {
				while (pHead2 != NULL && pHead2->val < pHead1->val) {
					preHead = pHead2;
					pHead2 = pHead2->next;
				}
				preHead->next = pHead1;
				nextHead = pHead1->next;
				pHead1->next = pHead2;
				pHead2 = preHead->next;
				pHead1 = nextHead;
			}
		}
		return Head;
	}
};

int main(void)  
{  
	ListNode a1(8), a2(12),
		     b1(5), b2(6), b3(7), b4(9);
	a1.next = &a2;

	b1.next = &b2;
	b2.next = &b3;
	b3.next = &b4;
	Solution s;
	ListNode *Head = NULL;
	Head = s.Merge(&a1, &b1);
	return 0;  
}
二、递归实现

#include <iostream>

using namespace std;

struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
		val(x), next(NULL) {
	}
};

class Solution {
public:
	ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
		ListNode *Head = NULL;
		//输入合法性检测,也作为递归的终止条件
		if (pHead1 == NULL){
			return pHead2;
		}
		if (pHead2 == NULL) {
			return pHead1;
		}
		/*
		 拿情况pHead1->val <= pHead2->val为例进行说明:
		 Merge(pHead1->next, pHead2)返回的肯定是已经排好序的链表(假设是X),
		 由于当前pHead1->val <= pHead2->val,所以只有pHead1能拿到后继X的资格
		*/
		if (pHead1->val <= pHead2->val) {
			pHead1->next = Merge(pHead1->next, pHead2);
			return pHead1;
		}
		else {
			pHead2->next = Merge(pHead1, pHead2->next);
			return pHead2;
		}
	}
};

int main(void)  
{  
	ListNode a1(8), a2(12),
		     b1(5), b2(6), b3(7), b4(9);
	a1.next = &a2;

	b1.next = &b2;
	b2.next = &b3;
	b3.next = &b4;
	Solution s;
	ListNode *Head = NULL;
	Head = s.Merge(&b1, &a1);
	return 0;  
}





0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:7513次
    • 积分:226
    • 等级:
    • 排名:千里之外
    • 原创:16篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类