两两反转单向链表 (reverse a singly linked list in pair ) [#22]

两两反转单项链表就是把每两个数反转一次。如下:

A -> B -> C ->D -> E -> F ->G -> H -> I 两两反转后变为B -> A -> D ->C -> F -> E ->H -> G -> I

分析:

我们需要两个“指针”指着当前要反转的两个值。两两反转后,我们还需要记录下一个的值,换句话说,我们反转 A 和 B 后, 需要记录 C 值,我们才能够不断向下走,直到到达链表末端,所以,我们还需要另一个指向下一个值的“指针”。

反转以后,A的下一个是C, 但是,实际上,A的下一个应该是D,所以,每次反转时,我们需要更新前一个值的下一个值,也就是说把 A -> C 改成 A -> D。

所以,要完成这个操作,我们总共需要4个“指针”。

代码:

class Node {
	char value;
	Node next;	
}

public static Node reverseInPair(Node current) {
	if (current == null || current.next == null) return current;
	
	Node head = current.next;//save the head of the list
	Node previousNode = null;
	
	while(current != null && current.next != null) {
		//get the current node's next and "nextnext" node
		Node nextNode = current.next;
		Node nextNextNode = nextNode.next;
		
		//exchange the "next" node
		nextNode.next = current;
		current.next = nextNextNode;
		
		//update the "next" value of the previous node 
		if (previousNode != null) {
			previousNode.next = nextNode;
		}
		previousNode = current;
		current = nextNextNode;
	}
	
	return head;
} 

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


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值