寒假算法学习03
10-6编写一个具有以下原型的函数模板:
template
void exchange (list
iterator p2);
该模板用于将l1链表的[p1,l1.end())区间和l2链表的[p2,l2.end())区间的内容
交换。在主函数中调用该模板,以测试该模板的正确性。
#include <iostream>
#include <list>
using namespace std;
// function template to exchange the contents of two list segments
template <class T>
void exchange (list<T>& l1, typename list<T>::iterator p1, list<T>& l2, typename list<T>::iterator p2) {
// swap the elements from p1 to l1.end() with the elements from p2 to l2.end()
while (p1 != l1.end() && p2 != l2.end()) {
swap(*p1, *p2);
p1++;
p2++;
}
// if one list segment is longer than the other, append the remaining elements to the other list
if (p1 != l1.end()) {
l2.splice(l2.end(), l1, p1, l1.end());
}
else if (p2 != l2.end()) {
l1.splice(l1.end(), l2, p2, l2.end());
}
}
// main function to test the template
int main() {
// create two lists of integers
list<int> l1 = {1, 2, 3, 4, 5};
list<int> l2 = {6, 7, 8};
// print the original lists
cout << "l1: ";
for (int x : l1) {
cout << x << " ";
}
cout << endl;
cout << "l2: ";
for (int x : l2) {
cout << x << " ";
}
cout << endl;
// get iterators to the second element of each list
auto p1 = l1.begin();
p1++;
auto p2 = l2.begin();
p2++;
// call the exchange template function
exchange(l1, p1, l2, p2);
// print the modified lists
cout << "After exchange:" << endl;
cout << "l1: ";
for (int x : l1) {
cout << x << " ";
}
cout << endl;
cout << "l2: ";
for (int x : l2) {
cout << x << " ";
}
cout << endl;
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构