Swift - LeetCode - 分隔链表

作者: 依赖糊涂 | 来源:发表于2019-03-04 13:48 被阅读4次

题目

分隔链表

问题:

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x 的节点之前。你应当保留两个分区中每个节点的初始相对位置。

示例:

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

解题思路:

这个题一直把我搞在蒙圈的路上、不知道有没有人和我一样总认为 value =4的节点要放到value =3节点后面。

代码:
/**
public class SingNode {
    public var value : Int
    public var nextNode: SingNode?
    
    public init(value:Int) {
        self.value = value
    }
}

extension SingNode : CustomStringConvertible {
    public var description: String {
        var string = "\(value)"
        var node = self.nextNode
        
        while node != nil {
            string = string + " -- " + "\(node!.value)"
            node = node?.nextNode
        }
        return string
    }
}
 **/
      
func partition(_ head: SingNode?, _ x: Int) -> SingNode? {
        let prevDummy = SingNode.init(value: 0)
        var prev = prevDummy
        let postDummy = SingNode.init(value: 0)
        var post = postDummy
        
        var node = head

        while node != nil {
            if node!.value < x {
                prev.nextNode = node
                prev = node!
            } else {
                post.nextNode = node
                post = node!
            }
            node = node!.nextNode
        }
        
        post.nextNode = nil
        prev.nextNode = postDummy.nextNode
   
        return prevDummy.nextNode
    }
    

相关文章

  • Swift - LeetCode - 分隔链表

    题目 分隔链表 问题: 给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于或等于 x ...

  • Leetcode归类

    链表: Leetcode-725:分隔链表

  • leetcode链表之分隔链表

    86、分隔链表[https://leetcode-cn.com/problems/partition-list/]...

  • leetcode链表之分隔链表

    725、分隔链表[https://leetcode-cn.com/problems/split-linked-li...

  • 86. 分隔链表

    86. 分隔链表[https://leetcode-cn.com/problems/partition-list/...

  • 86. 分隔链表

    86. 分隔链表[https://leetcode.cn/problems/partition-list/] 给你...

  • 725. 分隔链表

    725. 分隔链表[https://leetcode-cn.com/problems/split-linked-l...

  • LeetCode 86 ——分隔链表

    1. 题目 2. 解答 从前向后遍历链表,将结点值小于 x 的结点放入到新链表 1 中,将结点值大于等于 x 的结...

  • LeetCode 86 分隔链表

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

  • LeetCode - #86 分隔链表

    前言 我们社区陆续会将顾毅(Netflix 增长黑客,《iOS 面试之道》作者,ACE 职业健身教练。)的 Swi...

网友评论

    本文标题:Swift - LeetCode - 分隔链表

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