【发布时间】:2014-11-26 15:34:31
【问题描述】:
假设我在单链表中有一个头指针 H,我将如何在伪代码中完成此操作? 反转 H 指向的单链表中的节点。 注意:不能有新的节点 创建的。
【问题讨论】:
标签: data-structures linked-list nodes reverse
假设我在单链表中有一个头指针 H,我将如何在伪代码中完成此操作? 反转 H 指向的单链表中的节点。 注意:不能有新的节点 创建的。
【问题讨论】:
标签: data-structures linked-list nodes reverse
你可以通过将问题拆分为第一个节点和剩余节点,将剩余节点反转,然后将新的最后一个节点指向第一个节点来递归解决它。递归堆栈的每一层都从调用它的层的“rest”节点开始
reverse(node header){
//Return if empty list.
if (h == null) return
//Split the problem into first and rest.
node first = header.start
node rest = first.next
//Return if only one node.
if (rest == null) return
//reverse the rest of the problem, and then point the end of the rest to the old first.
header.start = rest
reverse(header)
first.next.next = first
//Set the old first to null, as it is now the last node in the list.
first.next = null
//Point the header H to the new first node.
H.next = rest
}
这简化为不使用指针,如果您可以在伪代码中使用指针,则可以将指向“rest”节点的指针传递给每个后续递归层。
【讨论】: