合併兩個有序鏈表——題集(一)
今天分享三道數據結構的題,分別是合併兩個有序鏈表,合併以後的鏈表依舊有序;實現1+2+3...+n,要求不能使用乘除法、循環、條件判斷、選擇相關的關鍵字;求兩個整數之和,不得使用四則運算。
合併兩個有序鏈表,合併以後的鏈表依舊有序:
代碼如下:
#include<iostream>
using namespace std;
//--合併兩個有序鏈表,合併以後的鏈表依舊有序。
struct ListNode{
int val;
ListNode* next;
ListNode(int _val)
:val(_val)
,next(NULL)
{}
};
ListNode* Merge(ListNode* l1,ListNode* l2){//l1,l2爲升序
if(l1 == NULL)return l2;
if(l2 == NULL)return l1;
ListNode* head;
ListNode* tail;
head=l1;//默認升序
if(l1->val > l2->val){
head = l2;
l2 = l2->next;
}
else{
l1 = l1->next;
}
tail = head;
while(l1 != NULL && l2 != NULL){
if(l1->val > l2->val){
tail->next = l2;
l2 = l2->next;
}
else{
tail->next=l1;
l1 = l1->next;
}
tail = tail->next;
}
if(l1 != NULL){
tail->next = l1;
}
else{
tail->next = l2;
}
return head;
}
void Printf(ListNode* l1){//打印
while(l1!=NULL){
cout<<l1->val<<" ";
l1=l1->next;
}
printf("\n");
}
void Listtest(){
ListNode lA1(1);
ListNode lA2(2);
ListNode lA3(3);
ListNode lA4(4);
lA1.next = &lA2;
lA2.next = &lA3;
lA3.next = &lA4;
ListNode lB1(1);
ListNode lB2(4);
ListNode lB3(6);
ListNode lB4(8);
ListNode lB5(11);
lB1.next = &lB2;
lB2.next = &lB3;
lB3.next = &lB4;
lB4.next = &lB5;
cout<<"合併兩個有序鏈表,合併以後的鏈表依舊有序。"<<endl;
cout<<"lA(默認升序): ";
Printf(&lA1);
cout<<"lB(默認升序): ";
Printf(&lB1);
ListNode* tmp = Merge(&lA1, &lB1);
cout<<"lAlB合併後: ";
Printf(tmp);
}
int main(){
Listtest();//合併兩個有序鏈表,合併以後的鏈表依舊有序。
system("pause");
return 0;
}
運行結果
實現1+2+3...+n,要求不能使用乘除法、循環、條件判斷、選擇相關的關鍵字:
利用遞歸:
原代碼如下:
#include<iostream>
using namespace std;
//--實現1+2+3...+n,要求不能使用乘除法、循環、條件判斷、選擇相關的關鍵字。
int Summation(int n){
int sum=n;
bool s = (n>0)&&(sum += Summation(n-1));
return sum;
}
int main(){
cout<<"1-5依次相加:"<<Summation(5)<<endl;
////7.13////--實現1+2+3...+n,要求不能使用乘除法、循環、條件判斷、選擇相關的關鍵字。
cout<<"1-100依次相加:"<<Summation(100)<<endl;
cout<<"1-2155依次相加:"<<Summation(2155)<<endl;
system("pause");
return 0;
}
運行界面
求兩個整數之和,要求在函數體內不得使用+、-、*、/四則運算符號:
思路:使用位運算,可用&,|,^;異或:相同爲0,相異爲1(沒有進位,各位相加的值);&:同1爲1(進位)。
遞歸源代碼:
#include<iostream>
using namespace std;
//求兩個整數之和,要求在函數體內不得使用+、-、*、/四則運算符號:
int TwoSum(int a, int b){
if(a==0)return b;
if(b==0)return a;
int tmp = a^b;
int carry = a&b;
return TwoSum(tmp,carry);
}
int main(){
cout<<"8+12="<<TwoSum(8, 12)<<endl;
//7.13//求兩個整數之和,要求在函數體內不得使用+、-、*、/四則運算符號
cout<<"63+127="<<TwoSum(63, 127)<<endl;
cout<<"255+517="<<TwoSum(255, 517)<<endl;
system("pause");
return 0;
}
運行界面
分享如上!
PS:題集這一類,大多隻有代碼和運行結果,思路少有,視具體情況而定!