码迷,mamicode.com
首页 > 其他好文 > 详细

Swap Nodes in Pairs

时间:2018-08-28 22:05:17      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:des   value   should   air   example   nbsp   lis   color   when   

Swap Nodes in Pairs

https://www.youtube.com/watch?v=f45_eF1gmn8&t=83s




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.



class Solution {
    public ListNode swapPairs(ListNode head) {
        // base case
        if(head == null || head.next == null){
            // size = 0 , size = 1 
            return head;
        }
        
        // recursion
        ListNode node1 = head.next;
        ListNode next = node1.next;
        node1.next = head;
        head.next = swapPairs(next);
        return node1;
    }
}

// when size = 2, npe won‘t appear 
// NullPointerException is a RuntimeException . In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when an application attempts to use an object reference that has the null value. These include: Calling an instance method on the object referred by a null reference.

 

Swap Nodes in Pairs

标签:des   value   should   air   example   nbsp   lis   color   when   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9550928.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!