24. Swap Nodes in Pairs

给定一个链表,交换每两个相邻节点并返回其头部。

例如,
给定1->2->3->4,你应该返回列表2->1->4->3

你的算法应该只使用恒定的空间。不能修改列表中的值,只有节点本身可以​​更改。

/**
 * 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 n=head.next;
        head.next=swapPairs(head.next.next);
        n.next=head;
        return n;
    }
}

 

posted @ 2018-04-08 19:37  苏子子木  阅读(88)  评论(0编辑  收藏  举报