题目
24. 两两交换链表中的节点
思路
最开始自己画,越画越复杂比较复杂,写不出来!(呜呜)去看了解题思路,发现只需要三步。,按以下思路写了代码,循环停止那里的条件我还以有更好的写法,发现给出的写法是一样的,两个and条件有先后顺序的,不可交换。
代码
class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode cur = new ListNode();//虚拟节点
        ListNode out = head.next;
        cur.next = head;
        ListNode pre;//指向奇数节点 如节点1
        ListNode q;//指向偶数个节点 如节点2
        ListNode temp;
        while (cur.next != null && cur.next.next != null){//这里会先判断cur.next是否为空,不为空的情况下再判断cur.next.next是否为空 因为链表为奇数的情况下只需要交换一次
            pre = cur.next;
            q = pre.next;
            temp = q.next;
            cur.next = q;
            q.next = pre;
            pre.next = temp;
            cur = pre;
        }
//        System.out.println("head:"+head);
        return out;
    }
}
                



















