21. 合并两个有序链表

时间:2019-08-26
本文章向大家介绍21. 合并两个有序链表,主要包括21. 合并两个有序链表使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

/*
解题思路:
新建一个链表,然后比较两个链表中的元素值,把较小的那个链到新链表中,
由于两个输入链表的长度可能不同,所以最终会有一个链表先完成插入所有元素,
则直接另一个未完成的链表直接链入新链表的末尾。
*/
#define  _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}

};
class Solution {
public:
	ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
		ListNode *dummy = new ListNode(-1), *cur = dummy;
		while (l1 && l2) {
			if (l1->val < l2->val) {
				cur->next = l1;
				l1 = l1->next;
			}
			else {
				cur->next = l2;
				l2 = l2->next;
			}
			cur = cur->next;
		}
		cur->next = l1 ? l1 : l2;
		return dummy->next;
	}
};
ListNode* CreateListNode(int arr[], int n)
{
	ListNode* head;
	head = new ListNode(arr[0]);
	ListNode* cur;
	cur = head;
	for (int i = 1; i < n; i++)
	{
		cur->next = new ListNode(arr[i]);
		cur = cur->next;
	}
	return head;
}
int main()
{
	int n, m;
	cin >> n >> m;
	int i;
	int a[100];
	for (i = 0; i < n; i++)
	{
		scanf("%d", &a[i]);
	}
	ListNode* head = CreateListNode(a, n);
	int j;
	int b[100];
	for (j = 0; j < m; j++)
	{
		scanf("%d", &b[j]);
	}
	ListNode* head1 = CreateListNode(b, m);
	ListNode* result = Solution().mergeTwoLists(head, head1);
	while (result != NULL)
	{
		printf("%d ", result->val);
		result = result->next;
	}
	system("pause");
	return 0;

}

  

原文地址:https://www.cnblogs.com/277223178dudu/p/11410966.html