24. Swap Nodes in Pairs

来源:互联网 发布:阿里云 混合云 编辑:程序博客网 时间:2024/06/06 07:26
/**
 * 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 || head.next == null){
            return head;
        }
        ListNode node = head.next;
        head.next = swapPairs(head.next.next);
        node.next = head;
        return node;
    }

}

使用递归即可

原创粉丝点击