倒排一个LinkedList

问题:

给一个单向链表,把它从头到尾反转过来。比如: a -> b -> c ->d 反过来就是 d -> c -> b -> a 。

分析:

假设每一个node的结构是:

class Node {
	char value;
	Node next;
}

非递归反转:

//非递归实现
	public Node reverse(Node current) {
		Node previous = null;
		Node next = null;
		
		while (current != null) {
			//存储下一节点
			next = current.next;
			current.next = previous;		//反转
			
			//更新遍历节点
			previous = current;
			current = next;
		}
		
		return current;
	}

递归反转:利用递归走到链表的末端,然后再更新每一个node的next 值

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

你可能感兴趣的:(#,算法调优)