public static void main(String[] args) { Node n6 = new Node(6); Node n5 = new Node(5); n5.next = n6; Node n4 = new Node(4); n4.next = n5; Node n3 = new Node(3); n3.next = n4; Node n2 = new Node(2); n2.next = n3; Node n1 = new Node(1); n1.next = n2; Node tmp = new Test().exchangeNode2(n1); System.out.println(n1); } public Node exchangeNode2(Node head) { Node first = new Node(-1); first.next = head; Node curr = first; Node p1 = null; Node p2 = null; Node p2Next = null; for (; curr.next != null && curr.next.next != null; ) { p1 = curr.next; p2 = p1.next; p2Next = p2.next; curr.next = p2; p2.next = p1; p1.next = p2Next; curr = p1; } return first.next; }
结果:
1,2,3,4,5,6 -》2,1,4,3,6,5