It takes time to judge the case where an odd number of nodes and an even number of nodes are required.
Package Level2; import Utility. listNode;/*** Swap Nodes in Pairs *** Given a linked list, swap every two adjacent nodes and return its head. for example, Given 1-> 2-> 3-> 4, you should return the list as 2-> 1-> 4-> 3. your algorithm shocould use only constant space. you may not modify the values in the list, only nodes itself can be changed. **/public class S24 {public static void main (String [] args) {ListNode n1 = new ListNode (1); ListNode n2 = new ListNode (2); n1.next = n2; ListNode n3 = new ListNode (3); n2.next = n3; n1.print (); ListNode head = swapPairs (n1); head. print ();} public static ListNode swapPairs (ListNode head) {if (head = null) {return null;} // if there is only one element, if (head. next = null) {return head;} ListNode I = head; // I points to 1st ListNode j = I. next; // j points to 2nd ListNode k = j. next; // K points to 3rd head = head. next; while (j! = Null) {j. next = I; if (k! = Null & k. next! = Null) {// when there is an even number of nodes I. next = k. next;} else {// when there is an odd number of nodes I. next = k;} // update the values of I, j, and k, forward two cells I = k; if (k! = Null) {j = k. next;} else {j = null;} if (k! = Null & k. next! = Null) {k = k. next. next;} else {k = null ;}} return head ;}}