反转单向链表(reverse a singly linked list)



问题:

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

这里讲解两种方法:

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

  1. public static Node reverse(Node head) {  
  2.     Stack<Node> stack = new Stack<Node>();  
  3.       
  4.     // put all the nodes into the stack  
  5.     while (head != null) {  
  6.         stack.add(head);  
  7.         head = head.next();  
  8.     }  
  9.       
  10.     //reverse the linked list  
  11.     Node current = stack.pop();  
  12.     head = current;  
  13.     while (stack.empty() != true) {  
  14.         Node next = stack.pop();  
  15.         //set the pointer to null, so the last node will not point to the first node.  
  16.         next.setNext(null);  
  17.         current.setNext(next);  
  18.         current = next;  
  19.     }  
  20.       
  21.     return head;      
  22. }  
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;	
}

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

  1. public static Node reverse(Node head) {  
  2.     Node previous = null;  
  3.   
  4.     while (head != null) {  
  5.         Node nextNode = head.next();  
  6.         head.setNext(previous);  
  7.         previous = head;  
  8.         head = nextNode;  
  9.     }  
  10.           
  11.     return previous;      
  12. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值