單連結串列-相鄰節點交還

地瓜的土豆發表於2020-12-11

題目:
把連結串列相鄰元素翻轉,例如給定連結串列為卜>2一>3一對一>5->6一>7,則翻轉後的連結串列變為
2一> 1一>4一>3一>6一>5一>7 。


class LNode:
    def __init__(self, data):
        self.data = data
        self.next = None


head = LNode(None)

l1 = LNode(1)

l2 = LNode(2)
l3 = LNode(3)
l4 = LNode(4)
l5 = LNode(5)
l6 = LNode(6)
l7 = LNode(7)


head.next = l1
l1.next = l2
l2.next = l3
l3.next = l4
l4.next = l5
l5.next = l6
l6.next = l7


def test(head):
    temp = head
    l1 = head.next
    l2 = head.next.next

    while True:
        if l2:
            temp.next = l2
        else:
            temp.next = l1
            break
        temp = l2
        l2 = temp.next
        temp.next = l1
        temp = l1
        l1 = l2
        if l1:
            l2 = l1.next
        else:
            temp.next = None
            break


if __name__ == '__main__':
    test(head)
    temp = head
    while temp is not None:
        print(temp.data)
        temp = temp.next

相關文章