LeetCode:24 两两交换链表中的节点

class Solution {

    public ListNode reverse(ListNode a,ListNode b){
           
        a.next = b.next;
        b.next = null;
        b.next = a;
        return b;
    }

    public ListNode swapPairs(ListNode head) {
        ListNode t = new ListNode(0);
        ListNode tmp = head;
        int len=0;
        while(tmp!=null){
            len++;
            tmp=tmp.next;
        }
        if(head==null){
            return null;
        }
        if(len==1){
            return head;
        }
        ListNode prev = t;
        len /= 2;
        for(int i=1;i<=len;i++){
            tmp = reverse(head,head.next);
            prev.next = tmp;
            prev = tmp.next;
            if(head.next!=null)
                head = head.next;
             
        }
        return t.next;
    }
}

 

posted @ 2020-10-09 10:07  dlooooo  阅读(104)  评论(0编辑  收藏  举报