C++ 合并方法C++;
我想写一个方法,以交替的方式将两个列表合并在一起。如果我有list1=(0,1,2,3,4)和list2=(5,6,7,8),那么最终的列表应该是(0,5,1,6,2,7,3,8,4)。你有什么想法或提示吗,因为我尝试了很多东西,但都没有意义。如果你不需要保持原始列表的完整性,那就很简单了 算法看起来像这样:C++ 合并方法C++;,c++,C++,我想写一个方法,以交替的方式将两个列表合并在一起。如果我有list1=(0,1,2,3,4)和list2=(5,6,7,8),那么最终的列表应该是(0,5,1,6,2,7,3,8,4)。你有什么想法或提示吗,因为我尝试了很多东西,但都没有意义。如果你不需要保持原始列表的完整性,那就很简单了 算法看起来像这样: 从列表1的开头开始,转到项目1(1.1) 从列表2中选择相应的项(2.1),将其头更改为列表1头,将其上一个更改为列表1当前项(1.1),将当前项下一个指针更改为2.1,并将1'下一个指针
问题是,当我们操纵和做这些任务时,我们失去了1.2的指针,我们失去了很多东西的轨迹。这就是为什么意大利面飞碟发明了临时变量,我猜你昨天也问了同样的问题。
// I've been doing Java for a few years now, so my pointers are a bit rusty...
// Forgive pointer errors and focus on concept
/**
* @Param list1 the pointer to the head of the first list
* @Param list2 the pointer to the head of the second list
* Assumption - list 1 will be able to swallow list 2 without overflowing
* handling that is left to OP
*/
void mergeInto(Node *list1, Node *list2) {
Node curr1 = list1;
Node curr2 = list2;
while(curr2 != null) {
// store after nodes
Node after1 = curr1.next;
Node after2 = curr2.next;
// link curr2 into list1
curr1.next = curr2;
curr2.prev = curr1;
after1.prev = curr2;
curr2.next = after1;
// move on to the next in list2
curr2 = after2;
}
}