algorithm - 如何在不修改指针的情况下递归地反转单链表?

标签 algorithm recursion linked-list

最近面试,面试官让我在不修改指针(只改变值)的情况下反转一个单向链表。 一开始我想出了一个使用堆栈的解决方案。他说没关系,并希望我递归地做。然后我给了他一个O(n^2)的解。但是他说他需要一个 O(n) 的解决方案。

谁能帮帮我?

最佳答案

伪代码

reverse (list):
 reverse2 (list, list)

reverse2 (a, b):
 if b != nil:
  a = reverse2 (a, b.next)
  if a != nil:
   swap (a.data, b.data)
   if a == b || a.next == b:
    # we've reached the middle of the list, tell the caller to stop
    return nil
   else:
    return a.next
  else:
   # the recursive step has returned nil, they don't want us to do anything
   return nil
 else:
  # we've reached the end of the list, start working!
  return a

关于algorithm - 如何在不修改指针的情况下递归地反转单链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35307526/

相关文章:

c# - 用C#实现Hoey Shamos算法

haskell - 如何在 Idris Interactive 中评估此递归函数?

c++11 - 为什么在使用异步操作时没有堆栈溢出?

c - 查找段错误

java - 查找链表中倒数第 k 个元素

c++ - 对象的二维几何布局

algorithm - 使用 Haskell Repa 数组实现相位展开算法

algorithm - btree 插入的一个特殊问题

c# - 具有递归的重复算法的排列

C : Load data from file to the linked list