合并两个有序链表——题集(一)
今天分享三道数据结构的题,分别是合并两个有序链表,合并以后的链表依旧有序;实现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:题集这一类,大多只有代码和运行结果,思路少有,视具体情况而定!