解题思路
这道题用画图的方法是比较好的。
相关代码
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode swapPairs(ListNode head) {ListNode H = new ListNode(0);H.next = head;ListNode p1 = H;ListNode p2 = H.next;if(p2==null){return H.next;}ListNode p3 = H.next.next;while(p1!=null&&p2!=null&&p3!=null){ListNode p4 = p3.next;p1.next = p3;p3.next = p2;p2.next = p4;ListNode t1 = p2;ListNode t2 = p4;if(p4 == null){break;}ListNode t3 = p4.next;p1 = t1;p2 = t2;p3 = t3;}return H.next; }
}