[LeetCode]24. Swap Nodes in Pairs两两交换链表中的节点

Given a linked list, swap every two adjacent nodes and return its head.

Example:

Given 1->2->3->4, you should return the list as 2->1->4->3.

Note:

  • Your algorithm should use only constant extra space.
  • You may not modify the values in the list's nodes, only nodes itself may be changed.

要求把相邻的2个节点两两互换,还必须是换指针而不能是只换值

这里我们用递归的方法来处理,两个指针l1和l2,l1-->l2,我们先把l1和l2换了,然后对l1.next.next继续相同的方法递归下去

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

猜你喜欢

转载自www.cnblogs.com/jchen104/p/10262447.html