问题:
给一个单向链表,把它从头到尾反转过来。比如: a -> b -> c ->d 反过来就是 d -> c -> b -> a 。
分析:
假设每一个node的结构是:
- class Node {
- char value;
- Node next;
- }
因为在对链表进行反转的时候,需要更新每一个node的“next”值,但是,在更新 next 的值前,我们需要保存 next 的值,否则我们无法继续。所以,我们需要两个指针分别指向前一个节点和后一个节点,每次做完当前节点“next”值更新后,把两个节点往下移,直到到达最后节点。
代码如下:
- public Node reverse(Node current) {
- //initialization
- Node previousNode = null;
- Node nextNode = null;
- while (current != null) {
- //save the next node
- nextNode = current.next;
- //update the value of "next"
- current.next = previousNode;
- //shift the pointers
- previousNode = current;
- current = nextNode;
- }
- return previousNode;
- }
上面代码使用的是非递归方式,这个问题也可以通过递归的方式解决。代码如下:
- public Node reverse(Node current)
- {
- if (current == null || current.next == null) return current;
- Node nextNode = current.next;
- current.next = null;
- Node reverseRest = reverse(nextNode);
- nextNode.next = current;
- return reverseRest;
- }
本文介绍两种实现单向链表反转的方法:非递归和递归方式。非递归方式通过迭代更新节点的指向来完成反转过程;递归方式则巧妙地利用递归特性,先到达链表末尾再逐级反转节点指向。
594

被折叠的 条评论
为什么被折叠?



