Problem: 交换相邻的两个节点
 
LeetCode 24 Swap Nodes in Pairs (交换相邻节点)
 
  如上图所示,递归进行交换。从最尾端开始,当最尾端只有一个节点时,停止交换
  否则执行 swap(head.next) 
 
参考代码:
 
package leetcode_50;

/**
 * 
 * @author pengfei_zheng
 * 交换相邻节点
 */
public class Solution24 {
    public class ListNode {
          int val;
          ListNode next;
          ListNode(int x) { val = x; }
      }
     
    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;
    }
}

 

 

相关文章:

  • 2021-05-18
  • 2021-06-02
  • 2021-09-24
  • 2021-10-31
  • 2022-01-26
  • 2021-07-05
  • 2021-06-27
猜你喜欢
  • 2021-06-22
  • 2021-09-09
  • 2021-12-14
  • 2021-10-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案