华为OD机试真题2023_Swift_100_寻找链表的中间结点

2023-03-12  本文已影响0人  雾中探雪
// 寻找链表的中间结点
    func HW2023019() {
        var listArr: [String] = []
        // 测试用例
//        let line1 = "00100 4"
//        listArr = ["00000 4 -1", "00100 1 12309", "33218 3 00000", "12309 2 33218"]
//        let line1 = "10000 3"
//        listArr = ["76892 7 12309", "12309 5 -1", "10000 1 76892"]
        //  开始代码
        let line1 = String(readLine()!)
        let inputArr = line1.components(separatedBy: " ")
        while let line = readLine() {
            listArr.append(String(line))
        }
        var nodeArr: [[String]] = []
        var headNode: Node? = nil
        for str in listArr {
            let temp = str.components(separatedBy: " ")
            if String(temp[0]) == String(inputArr[0]) {
                let nextNode: Node = Node.init(String(temp[2]), 0, Node())
                // 头部节点
                headNode = Node.init(String(temp[0]), Int(temp[1])!, nextNode)
            }else {
                nodeArr.append(temp)
            }
        }
        var node = headNode
        while node?.next?.addr != nil && node?.next?.data != nil {
            let addr = node?.next?.addr
            for (i,str) in nodeArr.enumerated() {
                if str[0] == addr {
                    var nextNode: Node? = nil
                    if str[2] != "-1" {
                        nextNode = Node.init(str[2], 0, Node())
                    }
                    node?.next = Node.init(String(str[0]), Int(str[1])!, nextNode ?? Node())
                    node = node?.next
                    nodeArr.remove(at: i)
                    break
                }
            }
        }
        
        var fast: Node? = headNode  // 快指针走两步
        var slow: Node? = headNode  // 慢指针走一步
        while fast != nil && fast?.next != nil {
            slow = slow?.next
            fast = fast?.next?.next
        }
        print(slow?.data ?? -1)
    }

class Node {
    var addr: String?
    var data: Int?
    var next: Node?
    public init() {
        self.addr = nil
        self.data = nil
        self.next = nil
    }
    public init(_ addr: String?, _ data: Int?, _ next: Node?) {
        self.addr = addr
        self.data = data
        self.next = next
    }
}
上一篇 下一篇

猜你喜欢

热点阅读