【Leetcode鏈表】奇偶鏈表(328)

題目

給定一個單鏈表,把全部的奇數節點和偶數節點分別排在一塊兒。請注意,這裏的奇數節點和偶數節點指的是節點編號的奇偶性,而不是節點的值的奇偶性。node

請嘗試使用原地算法完成。你的算法的空間複雜度應爲 O(1),時間複雜度應爲 O(nodes),nodes 爲節點總數。算法

示例 1:code

輸入: 1->2->3->4->5->NULL
輸出: 1->3->5->2->4->NULL

示例 2:it

輸入: 2->1->3->5->6->4->7->NULL 
輸出: 2->3->6->7->1->5->4->NULL

說明:io

  • 應當保持奇數節點和偶數節點的相對順序。
  • 鏈表的第一個節點視爲奇數節點,第二個節點視爲偶數節點,以此類推。

解答

兩種方法:class

  • 奇數用一個頭結點,偶數用一個頭結點。而後將兩者相連。
  • 傻逼操做

經過代碼以下:List

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

class Solution:
    # 奇數用一個頭結點,偶數用一個頭結點。而後將兩者相連。
    # O(n),O(1)
    def oddEvenList(self, head: ListNode) -> ListNode:
        if not head:
            return head
        p = head
        t = q = p.next
        while p and p.next and q and q.next:
            p.next, q.next = p.next.next, q.next.next
            p, q = p.next, q.next
        p.next = t
        return head

    # 傻逼操做
    # O(n),O(1)
    # def oddEvenList(self, head: ListNode) -> ListNode:
    #     if not head or not head.next or not head.next.next:
    #         return head
        
    #     tail = head
    #     ans = 1
    #     while tail.next:
    #         ans += 1
    #         tail = tail.next
    #     wei = tail

    #     c = head
    #     p = 0
    #     while c != wei:
    #         if p == 1:
    #             break
    #         curr = c
    #         if ans%2==0 and curr.next == wei:
    #             p = 1
    #         n = c.next
    #         c.next = n.next
    #         tail.next = n
    #         tail = n
    #         c = n.next
    #     tail.next = None
    #     return head
相關文章
相關標籤/搜索