美文网首页
LeetCode之Merge In Between Linked

LeetCode之Merge In Between Linked

作者: 糕冷羊 | 来源:发表于2020-12-22 11:48 被阅读0次

    问题:



    方法:
    第一步,遍历list1,通过序号获取a对应的节点和b对应的节点;第二步,遍历list2获取尾部节点,然后把list2的头部接到a节点后,把b节点接到list2的尾部,最后返回list1的头部节点即可。

    class MergeInBetweenLinkedLists {
        fun mergeInBetween(list1: ListNode?, a: Int, b: Int, list2: ListNode?): ListNode? {
            var aNode: ListNode? = null
            var bNode: ListNode? = null
            var index = 0
            var cur = list1
            while (cur != null) {
                if (index == a - 1) {
                    aNode = cur
                }
                if (index == b + 1) {
                    bNode = cur
                }
                cur = cur.next
                index++
            }
            aNode?.next = list2
            cur = list2
            while (cur?.next != null) {
                cur = cur.next
            }
            cur?.next = bNode
            return list1
        }
    }
    
    fun main() {
    
    }
    

    有问题随时沟通

    具体代码实现可以参考Github

    相关文章

      网友评论

          本文标题:LeetCode之Merge In Between Linked

          本文链接:https://www.haomeiwen.com/subject/fdxsnktx.html