Algorithms—24.Swap Nodes in Pairs

来源:互联网 发布:爱知时计科技有限公司 编辑:程序博客网 时间:2024/06/14 07:16

思路:递归,然后交换相邻的两个值。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode swapPairs(ListNode head) {        if (head==null||head.next==null) {return head;}else {int val=head.val;head.val=head.next.val;head.next.val=val;head.next.next=swapPairs(head.next.next);}        return head;    }}


耗时:300ms,中下游


0 0