Swift-复杂链表的复制

题目:输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点).
核心代码:

`
func randomListNodeClone(headNode:inout RandomListNode?) {
var pHead:RandomListNode? = headNode
// A->B->C 拷贝 A->A1->B->B2->C->C1
while pHead != nil {
let cloneNode:RandomListNode = RandomListNode()
cloneNode.data = (pHead?.data)! + "1"
cloneNode.next = pHead?.next
pHead?.next = cloneNode

        pHead = cloneNode.next
    }
    // sibling 拷贝
    var sHead:RandomListNode? = headNode
    while sHead != nil {
        let nextNode:RandomListNode? = sHead?.next
        if nextNode != nil {
            nextNode!.sibling = sHead?.sibling?.next
        }
        sHead = sHead?.next?.next
    }
    
    // 拆分链表
    let cloneHead:RandomListNode? = headNode?.next
    headNode = cloneHead
    var beginNode:RandomListNode? = cloneHead
    while beginNode != nil {
        let temp = beginNode?.next?.next
        if beginNode?.next != nil {
            beginNode?.next = temp
        }
        beginNode = temp
    }
}`

测试代码:

`

var randomHead:RandomListNode = RandomListNode()
randomHead.data = "A"

var randomNode1:RandomListNode = RandomListNode()
randomNode1.data = "B"
randomHead.next = randomNode1

var randomNode2:RandomListNode = RandomListNode()
randomNode2.data = "C"
randomNode1.next = randomNode2

var randomNode3:RandomListNode = RandomListNode()
randomNode3.data = "D"
randomNode2.next = randomNode3

var randomNode4:RandomListNode = RandomListNode()
randomNode4.data = "E"
randomNode3.next = randomNode4

randomHead.sibling = randomNode2
randomNode1.sibling = randomNode4
randomNode3.sibling = randomNode1

var pHead:RandomListNode? = randomHead
var clone:RandomListClone = RandomListClone()
clone.randomListNodeClone(headNode: &pHead)
while pHead != nil {
print("FlyElephant-随机节点--(pHead!.data)-----(pHead!.sibling?.data)")
pHead = pHead?.next
}`


FlyElephant.png

你可能感兴趣的:(Swift-复杂链表的复制)