数据结构单链表

时间:2014-10-01 17:45:48

标签: data-structures linked-list nodes reverse

假设我在单链表中有一个头指针H,我将如何在伪代码中完成此操作? 反转H指向的单链表中的节点。注意:没有新节点可以 创建。

1 个答案:

答案 0 :(得分:0)

您可以通过将问题拆分为第一个节点和其余节点,反转剩余的节点,然后将新的最后一个节点指向第一个节点来递归地解决它。递归堆栈的每个级别都以" 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"节点到每个后续的递归层。

相关问题