两两反转单项链表就是把每两个数反转一次。如下:
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.youkuaiyun.com/beiyeqingteng/