(編程題)合併兩個有序鏈表,保持鏈表順序。
例如:
輸入:
鏈表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;
}