• 两两交换链表中的节点


    题目链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/

    注意这个交换不是这样的:1234-》2134-》2314-》2341
    这道题一旦1和2交换后,这两项就固定了,严格意义来说是一对一对相交换而不是相邻

    题解1

    此题我将两个节点交换单独做成了一个方法,这样比较直观。

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode swapPairs(ListNode head) {
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            ListNode h = dummy;
            while(h != null){
                helper(h);
                h = h.next==null? null:h.next.next;//保证交换过的不被再次交换
            }
            return dummy.next;
    
        }
         //node和node后面的节点交换,传入参数是node前面的指针。
        private void helper(ListNode preNode1){        
            ListNode preNode = preNode1;
            ListNode node = preNode.next;
            if(node == null) return;
            ListNode nodeNext = node.next;
            if(nodeNext == null) return;
            ListNode nodenextNext = nodeNext.next;
            //例如2134以3为node,preNode指向1,nodeNext指向4,nodenextNext指向null,交换后结果应该是2143
            preNode.next = node.next;//让1后面连上4
            nodeNext.next = node;//让4后面连上3
            node.next = nodenextNext;//让3后面连上之前4之后的数据
        }
    }
    
    

    题解2:大佬的递归。。。。

    class Solution {
        public ListNode swapPairs(ListNode head) {
            if(head == null || head.next == null){
                return head;
            }
            ListNode next = head.next;
            head.next = swapPairs(next.next);
            next.next = head;
            return next;
        }
    }
    
    

    看到这题解我裂开了。。。。我的代码真长。。。。。。

  • 相关阅读:
    oracle日志总结
    UIScrollView,contentOffset,contentInsert的各自特点和区别?
    js动态增加表格
    判断某个对象是不是DOM对象
    IOS 中frame与bounds的区别
    删除重复项,只取其中一条数据
    NSBundle
    React
    HTML5 postMessage 和 onmessage API 详解
    SonarQube
  • 原文地址:https://www.cnblogs.com/cstdio1/p/13545448.html
Copyright © 2020-2023  润新知