c - 使用递归的 ShuffleMerge

标签 c recursion linked-list tail-recursion

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);
  }
}

代码不起作用,无法访问 B 之后的元素...

最佳答案

这是一个简单的“笔和纸”调试 session ,使用我能想到的最简单的非平凡输入:

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

这就是代码在本例中应该做的事情吗?如果没有,为什么不呢?

我希望这项技术将来有用。

关于c - 使用递归的 ShuffleMerge,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12302624/

相关文章:

c - OpenMP : Creating threads, 并行性,循环障碍

c++ - C/C++ 中的非固定结构

c - 反转列表的一半

performance - `any`/`all` 的 Haskell/GHC 性能

c - fscanf返回值和链表

c - 如何使用 pthread、pthread_exit 将 * 转换为 double/float

c - 如何预加载大型数组以并行缓存?

string - 准备字符串中的重复字符 - 算法

c++ - 在我的递归函数中跟踪计数 (Collat​​z)

javascript - Tic-Tac-Toe 中的 Minimax 没有返回正确的值