• 24. Swap Nodes in Pairs


    package LeetCode_24
    
    /**
     * 24. Swap Nodes in Pairs
     * https://leetcode.com/problems/swap-nodes-in-pairs/description/
     *
     * Given a linked list, swap every two adjacent nodes and return its head.
    You may not modify the values in the list's nodes, only nodes itself may be changed.
    
    Example:
    Given 1->2->3->4, you should return the list as 2->1->4->3.
     * */
    class ListNode(var `val`: Int) {
        var next: ListNode? = null
    }
    
    class Solution {
        /*
        * Time complexity:O(n), Space complexity:O(1)
        * */
        fun swapPairs(head: ListNode?): ListNode? {
            if (head == null || head.next == null) {
                return head
            }
            val dummy = ListNode(-1)
            var prve = dummy
            var first: ListNode? = null
            dummy.next = head
            while (prve != null) {
                if (prve.next == null || prve.next!!.next == null) {
                    break
                }
                first = prve.next
                prve.next = first!!.next
                first.next = first.next!!.next
                prve.next!!.next = first
                prve = first
            }
            return dummy.next
        }
    }

    参考此文章

  • 相关阅读:
    币值转换
    抓老鼠啊~亏了还是赚了?
    第十二周作业
    第十一周作业
    第十周作业
    第九周作业
    第八周作业
    第七周作业
    第五周实验报告和总结
    第四次实验报告及总结
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/13631609.html
Copyright © 2020-2023  润新知