zoukankan      html  css  js  c++  java
  • leetcode刷题笔记八十六题 分隔链表

    leetcode刷题笔记八十六题 分隔链表

    源地址:86. 分隔链表

    问题描述:

    给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。

    你应当保留两个分区中每个节点的初始相对位置。

    示例:

    输入: head = 1->4->3->2->5->2, x = 3
    输出: 1->2->2->4->3->5

    /**
    本题较为简单,使用smaller链表连接小值,使用bigger链表连接大值,将small.next = biggerHead.next即可
    */
    /**
     * Definition for singly-linked list.
     * class ListNode(var _x: Int = 0) {
     *   var next: ListNode = null
     *   var x: Int = _x
     * }
     */
    object Solution {
        def partition(head: ListNode, x: Int): ListNode = {
            var start = head
            var smaller = new ListNode(0)
            var bigger = new ListNode(0)
            while(start.next != null){
                if(head.x < x){
                    smaller.next = head
                    smaller = smaller.next
                    start = start.next
                }
                else{
                    bigger.next = head
                    bigger = bigger.next
                    start = start.next
                }
            }
            println(head.toString)
            return ListNode(0)
        }
    }
    
  • 相关阅读:
    寒假作业4
    UVA5870 乱搞 Smooth Visualization
    UVA5874 Social Holidaying 二分匹配
    UVA5876 Writings on the Wall 扩展KMP
    hdu1231 最大连续子序列
    hdu3535 混合背包
    hdu3613 扩展KMP
    hdu4333 扩展KMP
    扩展KMP
    hdu4287 字典树
  • 原文地址:https://www.cnblogs.com/ganshuoos/p/13388806.html
Copyright © 2011-2022 走看看