The meaning of problems and ideas
Meaning of the questions: two nodes exchange (not the value of the exchange, the exchange node), not twenty-two exchange, if there are four on the front of the exchange, the latter two (emmm, self-understanding, my expression is slightly pale) .
Thinking: Maintenance three indicator variables, respectively, first, p, q. Where the first core node, to avoid the exchange of data chaos. p, q are two nodes need to exchange. See in particular code.
Attach mind map
Code
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode swapPairs(ListNode head) { if(head==null) return head; ListNode first,p,q,top = new ListNode(-1); top.next = head; first = top; p = top.next; q = p.next; while(p!=null && q!=null){ p.next = q.next; q.next = p; first.next = q; first = p; p = p.next; if(p==null) break; q = p.next; } return top.next; } }