反转单向链表(reverse a singly linked list)(单个反转) [# 7]

问题:

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

这里讲解两种方法:

第一种方法就是把每个Node按照顺序存入到一个stack里面,这样,最后面一个就在最上面了。然后,把每一个再取出来,这样顺序就换过来了。

public static Node reverse(Node head) {
	Stack<Node> stack = new Stack<Node>();
	
	// put all the nodes into the stack
	while (head != null) {
		stack.add(head);
		head = head.next();
	}
	
	//reverse the linked list
	Node current = stack.pop();
	head = current;
	while (stack.empty() != true) {
		Node next = stack.pop();
		//set the pointer to null, so the last node will not point to the first node.
		next.setNext(null);
		current.setNext(next);
		current = next;
	}
	
	return head;	
}

第二种方法就是利用两个指针,分别指向前一个节点和当前节点,每次做完当前节点和下一个节点的反转后,把两个节点往下移,直到到达最后节点。

public static Node reverse(Node head) {
	Node previous = null;

	while (head != null) {
		Node nextNode = head.next();
		head.setNext(previous);
		previous = head;
		head = nextNode;
	}
		
	return previous;	
}



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值