头条面试题. 链表排序(奇偶链表)

题目要求:

list奇数位升序,偶数位降序,让链表变成升序的
比如: 1 8 3 6 5 4 7 2 9 变成 1->2->3->4->...
拆分链表

代码:

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None


def sortList(head: ListNode) -> ListNode:
    if not head:
        return head
    # 拆链表,奇数的拆到一起, 偶数的拆到一起
    cur = head
    printList(head)
    head2 = None
    if cur.next:
        head2 = cur.next
        tmp = head2
    while cur.next and tmp.next:
        cur.next = tmp.next
        cur = cur.next
        tmp.next = cur.next
        tmp = tmp.next
    cur.next = None
    printList(head)
    printList(head2)
    # 偶数链表头为head2,逆序
    node = head2
    pre = None
    tmp = None
    while node:
        if node.next:
            tmp = node.next
            node.next = pre
            pre = node
            node = tmp
        else:
            node.next = pre
            break
        
    # 偶链表头head2 = node
    head2 = node
    # 链表合并
    cur = head
    tmp = head2
    printList(cur)
    printList(tmp)
    while cur and tmp:
        if cur.next:
            _next = cur.next
            cur.next = tmp
            cur = _next
            if tmp.next:
                _next = tmp.next
                tmp.next = cur
                tmp = _next
            else:
                tmp.next = cur
        elif tmp:
            cur.next = tmp
            break
        else:
            break
    printList(head)


def main():
    _list = [1, 6, 3, 4, 5, 2]
    # 构造链表
    head = ListNode(-1)
    node = head
    for i in _list:
        node.next = ListNode(i)
        node = node.next
    head = head.next
    printList(head)
    sortList(head)
    printList(head)


def printList(head: ListNode):
    result = ''
    while head:
        result += f'{head.val}' + '\t'
        head = head.next
    print(result)

if __name__ == "__main__":
    main()
posted @ 2019-10-31 13:07  Howardwang  阅读(837)  评论(0编辑  收藏  举报