題意:兩個節點交換(並非值交換,是節點的交換),並非兩兩交換,若是有四個就交換前面那個,後面兩個(emmm,自行理解,個人表達略顯蒼白)。spa
思路:維護三個指針變量,分別爲first、p、q。其中first爲核心節點,避免交換後,數據混亂。p、q分別爲兩個須要交換的節點。具體見代碼。指針
附上思惟圖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; } }