我正在开发一个功能,将2个单链表交织在一起(我已经完成了实验室,现在正在我自己的时间进行处理)而且我被卡住了。我已经尝试了很多东西,但我无法弄明白。谁能帮我吗?谢谢!
/**
* Create a new linked_list by merging two existing linked_lists.
* PRE: list1 is the first Node in a linked_list (if NULL, then it is empty)
* PRE: list2 is the first Node in another linked_list (if NULL, then it is empty)
* POST: A new linked_list is returned that contains new Nodes with the keys from
* the Nodes in list1 and list2, starting with the key of the first Node of list1,
* then the key of the first Node of list2, etc.
* When one list is exhausted, the remaining keys come from the other list.
* For example: [1, 2] and [3, 4, 5] would return [1, 3, 2, 4, 5]
*/
Node* interleave(Node* list1, Node* list2){
if (list1 == NULL && list2 == NULL) { return NULL; }
Node * p1 = list1;
Node * p2 = list2;
Node * newNode = new Node;
while (list1 != NULL && list2 != NULL) {
newNode->key = p1->key;
p1 = p1->next;
newNode->next->key = p2->key;
p2 = p2->next;
}
if (list1 == NULL && list2 != NULL) {
while (list2 != NULL) {
newNode->key = p2->key;
p2 = p2->next;
}
} else if (list2 == NULL && list1 != NULL) {
while (list1 != NULL) {
newNode->key = p1->key;
p1 = p1->next;
}
}
return newNode;
}