使用递归和非递归方式反转单向链表

问题:

给一个单向链表,把它从头到尾反转过来。比如: 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;
 }
递归的方法其实是非常巧的,它利用递归走到链表的末端,然后再更新每一个node的next 值 (代码倒数第二句)。 在上面的代码中, reverseRest 的值没有改变,为该链表的最后一个node,所以,反转后,我们可以得到新链表的head。

参考:
http://stackoverflow.com/questions/354875/reversing-a-linked-list-in-java-recursively

http://blog.csdn.net/beiyeqingteng/article/details/7030020

转载请注明出处:http://blog.csdn.net/beiyetengqing



  • 11
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值