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)
    }
}

猜你喜欢

转载自www.cnblogs.com/ganshuoos/p/13388806.html