C 使用递归进行洗牌
代码不工作,无法访问B之后的元素。这里是一个简单的“笔和纸”调试会话,使用我能想到的最简单的非平凡输入:C 使用递归进行洗牌,c,recursion,linked-list,tail-recursion,C,Recursion,Linked List,Tail Recursion,代码不工作,无法访问B之后的元素。这里是一个简单的“笔和纸”调试会话,使用我能想到的最简单的非平凡输入: struct node* ShuffleMerge(struct node* a, struct node* b) { struct node* result; struct node* recur; if (a==NULL) return(b); // see if either list is empty else if (b==NULL) return(a); else {
struct node* ShuffleMerge(struct node* a, struct node* b) {
struct node* result;
struct node* recur;
if (a==NULL) return(b); // see if either list is empty
else if (b==NULL) return(a);
else {
// it turns out to be convenient to do the recursive call first --
// otherwise a->next and b->next need temporary storage.
recur = ShuffleMerge(a->next, b->next);
result = a; // one node from a
a->next = b; // one from b
return(result);
}
}
这就是代码应该为这个案子做的吗?若否,原因为何
我希望这项技术在将来有用。我建议您尝试使用笔和纸进行调试,尽可能画出a和b的最简单的非平凡示例,然后逐步完成代码,一边编写每个变量的新值。那里至少有一个bug。
S(a=1->2, b=3->4) 1->2 2->N 3->4 4->N
recur := S(2, 4)
recur := S(a=N, b=N)
return N
recur := N
result:= 2
a := 2->4 1->2 2->4 3->4 4->N
recur := N
result:= 1->2->4
a := 1->3->4 1->3 2->4 3->4 4->N
return 1->3->4