我有解決方案代碼在這裏:交錯2鏈表C++
// Pre-condition: The fronts of two linked lists are provided.
// Post-condition: A linked list is returned that is the result of
// interleaving the elements from each provided list.
// (e.g. {1, 2, 3} & { 4, 5, 6} would return {1, 4, 2, 5, 3, 6}
Node* interleave(Node*& front1, Node*& front2) {
if(!front1) return front2;
if(!front2) return front1;
Node* third = front1->next; //this will become the third element
Node* fourth = front2->next; // this will be come the fourth element
front1->next = front2;
front2->next = third;
third = interleave(third, fourth);
return front1;
}
我有點明白,但我將永遠無法拿出這樣的事情,因爲我在遞歸很差勁。是否有另一種非遞歸方式來解決這個問題?如果是的話,你能給我一個提示嗎?我試過這個:
Node* interleave(Node*& front1, Node*& front2) {
Node* newNode = new Node;
while(front1!=NULL && front2!=NULL){
newNode = front1->next;
newNode = front2->next;
front1 = front1->next;
front2 = front2->next;
}
return newNode;
}
我敢肯定這是錯誤的,但這是我現在唯一能想出的東西。請幫忙。謝謝
這感覺就像一個功課問題。 – Lambdageek 2011-05-25 21:24:40
@Lambdageek:你的觀點? – 2011-05-26 06:26:23