Given a linked list, swap every two adjacent nodes and return its head.
 
For example,
Given1->2->3->4, You shoshould return the list2->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.
Original question link: https://oj.leetcode.com/problems/swap-nodes-in-pairs/ 
Question: Given a linked list, exchange two adjacent nodes and return.
 
Your algorithm can only use constant space. The values in the table cannot be modified, but only the nodes themselves can be changed.
 
Idea: first, directly switch the two nodesValue. Yes, but it does not.
 
 
public ListNode swapPairs(ListNode head) {if (head == null || head.next == null)return head;ListNode back = head;while (back != null) {if (back.next != null) {int val = back.val;back.val = back.next.val;back.next.val = val;back = back.next.next;} elsebreak;}return head;} 
 
2nd Methods: first set a virtual header node to avoid being empty. Then swap the reference of the node. 
 
public ListNode swapPairs(ListNode head) {ListNode dummy = new ListNode(-1);dummy.next = head;ListNode pre = dummy;while (head != null && head.next != null) {ListNode tmp = head.next.next;pre.next = head.next;head.next.next = head;head.next = tmp;pre = head;head = tmp;}return dummy.next;}