leetcode刷题笔记二十四 两两交换链表中的节点 Scala版本

leetcode刷题笔记二十四 两两交换链表中的节点 Scala版本

源地址:24. 两两交换链表中的节点

问题描述:

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.

代码补充:

//本题较为简单,通过scala的模式匹配,分为1节点为空,1节点不为空2节点为空及两节点都不为空的三种情况处理,其中 1 2两种情况一般出现在链表结尾,通过对3情况下,x1 x2节点交换位置并调用函数进行继续下去,需要注意的是节点next交换顺序
object Solution {
    def swapPairs(head: ListNode): ListNode = {
       if (head == null) return null
        (head, head.next) match {
            case(h,null) => h
            case(x1, x2) => {
                x1.next = swapPairs(x2.next)
                x2.next = x1
                x2
            }
        }
    }
}
posted @ 2020-04-23 19:58  ganshuoos  阅读(116)  评论(0编辑  收藏  举报