(编程题)合并两个有序链表,保持链表顺序。
例如:
输入:
链表1: 1->3->5->7
链表2: 2->4->6->8
输出:
链表交集: 1->2->3->4->5->6->7->8
一般做法:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
{
if(pHead1 == nullptr)
return pHead2;
if(pHead2 == nullptr)
return pHead1;
//ListNode resHead(0);
ListNode* dummy = new ListNode(-1);//创建新的头结点
ListNode* p = dummy;//p指向dummy,p指针向下移动,一直更新
while(pHead1 && pHead2){
if(pHead1->val < pHead2->val){
p->next = pHead1;//当前较小值为p1,连接到p指针后面
pHead1 = pHead1->next;//p1指针后移一位
}
else{
p->next = pHead2;
pHead2 = pHead2->next;
}
p = p->next;//p指针后移
}
if(pHead1)//如果最后剩下的是p1链表,则把p1连接到p上
p->next = pHead1;
if(pHead2)//如果最后剩下的是p2链表,则把p2连接到p上
p->next = pHead2;
return dummy -> next;
}
};
测试程序:
不一般做法:
#include <iostream>
#include <vector>
#include <list>
//#include <bits/stdc++.h>
using namespace std;
struct ListNode{
int val;
struct ListNode *next;
ListNode(int x):val(x),next(NULL){
}
};
ListNode* Merge(ListNode* l1, ListNode* l2){
if(l1 == nullptr)
return l2;
if(l2 == nullptr)
return l1;
ListNode* dummy = new ListNode(-1);
ListNode* 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;
}
if(l1)
cur->next = l1;
if(l2)
cur->next = l2;
return dummy->next;
}
ListNode* createList(vector<int>& num){
if(num.size()== 0) return nullptr;
ListNode* head = new ListNode(num[0]);
ListNode* cur = head;
for(int i = 1; i <num.size(); i++){
cur->next = new ListNode(num[i]);
cur = cur->next;
}
return head;
}
int main(int argc, char** argv) {
vector<int> num1,num2;
int n1, n2;
while(cin>>n1){
num1.push_back(n1);
if(cin.get() == '\n')
break;
}
while(cin>>n2){
num2.push_back(n2);
if(cin.get() == '\n')
break;
}
ListNode* head1 = createList(num1);
ListNode* head2 = createList(num2);
ListNode* res = Merge(head1, head2);
ListNode* p = res;
while(p){
cout<< p->val<<" ";
p = p->next;
}
return 0;
}
【数组】
链接:https://www.nowcoder.com/questionTerminal/27c833289e5f4f5e9ba3718ce9136759
来源:牛客网
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> nums1, nums2,nums;
int num1, num2;
while(cin >> num1)
{
nums1.push_back(num1);
nums.push_back(num1);
if(cin.get() == '\n')
break;
}
while(cin >> num2)
{
nums2.push_back(num2);
nums.push_back(num2);
if(cin.get() == '\n')
break;
}
sort(nums.begin(),nums.end());
for(int i=0;i<nums.size();i++)
cout<<nums[i]<<" ";
return 0;
}