24. 两两交换链表中的节点

[lc24]
https://leetcode-cn.com/problems/swap-nodes-in-pairs/

[brainstorm]
1-2-3-4 -> 2-1-4-3
1-2 -> 2-1
3-4 -> 4-3

why recursion rathen than iteration?
4 is linked list head of 4-3
which result of sub problem 3-4.

in summary, say merge sub1 and sub2
if sub2 result is needed in merge, recursion is better.
as by recursion, sub2 is handled before sub1.

sub1 1-2
sub2 3-4

[code]

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {

        return rev(head);        
    }

    ListNode rev(ListNode head){

        if(head==null || head.next==null){
            return head;
        }
        
        ListNode c2 = head.next;
        ListNode c3  = c2.next;
        c2.next = head;
        head.next = rev(c3);

        return c2;
    }
}```

你可能感兴趣的:(LC)