【python3】leetcode 143. Reorder List(Medium)

143. Reorder List(Medium)

Given a singly linked list LL0→L1→…→Ln-1→Ln,
reorder it to: L0→LnL1→Ln-1→L2→Ln-2→…

You may not modify the values in the list's nodes, only nodes itself may be changed.

Example 1:

Given 1->2->3->4, reorder it to 1->4->2->3.

Example 2:

Given 1->2->3->4->5, reorder it to 1->5->2->4->3.

 

1 list大法好  space O(n),time O(n)

找规律发现只要遍历一半linklist,linklist[i]指向reverse[i], reverse[i]指向linklist[i+1],最后的reverse[i]指向None就可以啦

linklist :1 2  | 3 4 

倒序:    4 3  |2 1

reseult :1-》4》2》3》null

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reorderList(self, head):
        """
        :type head: ListNode
        :rtype: void Do not return anything, modify head in-place instead.
        """
        if head and head.next and head.next.next:
            node = head
            linklist = []
            while(node):
                linklist.append(node)
                node = node.next
            revlinklist = list(reversed(linklist))
            for i in range(math.ceil(len(linklist)/2)):
                linklist[i].next = revlinklist[i]
                revlinklist[i].next = linklist[i+1]
                if i == math.ceil(len(linklist)/2)-1:   
                    revlinklist[i].next = None

2 使用双端队列colletions.deque,space O(n),time O(n)

交错popleft和pop

class Solution:
    def reorderList(self, head):
        """
        :type head: ListNode
        :rtype: void Do not return anything, modify head in-place instead.
        """
        if head and head.next and head.next.next:
            deque = collections.deque()
            node = head
            while(node):
                deque.append(node)
                node = node.next
            node = deque.popleft()
            while(deque):
                node.next = deque.pop()
                node = node.next
                if deque:               
                    node.next = deque.popleft()
                    node = node.next
            node.next = None

 

你可能感兴趣的:(leetcode,python)