zoukankan      html  css  js  c++  java
  • LeetCode 24 Swap Nodes in Pairs

    public class SwapNodesInPairs {
    
        /**
         * Definition for singly-linked list.
         * public class ListNode {
         * int val;
         * ListNode next;
         * ListNode(int x) { val = x; }
         * }
         */
        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 p = head;
                //next节点
                ListNode q = head.next;
                //before节点
                ListNode r = null;
                head = q;
                while (p != null && q != null) {
                    p.next = q.next;
                    q.next = p;
                    if (r != null) {
                        r.next = q;
                    }
                    //更新
                    r = p;
                    p = p.next;
    
                    if (p != null) {
                        q = p.next;
                    }
                }
                return head;
            }
        }
    }
    

    递归版本

    class Solution {
        public ListNode swapPairs(ListNode head) {
            if(head == null){
                return null;
            }
            if(head.next == null){
                return head;
            }
            ListNode next = head.next;
            //交换后的头结点的下一个节点是 下一对节点的尾节点
            head.next = swapPairs(next.next);
            next.next = head;
            return next;
        }
        
    }
    
  • 相关阅读:
    SpringCloud Gateway使用实例
    Nacos服务注册与发现
    HashMap源码分析——put方法
    Volatile关键字——内存可见性
    Java的JIT编译器
    why spring?
    mysql 锁
    sql server 表变量和临时表
    mysql 存储过程
    mysql 截取字符串
  • 原文地址:https://www.cnblogs.com/sansamh/p/9074871.html
Copyright © 2011-2022 走看看