1. 程式人生 > >[LeetCode]24. Swap Nodes in Pairs兩兩交換連結串列中的節點

[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; } }