给定一个单链表,把全部的奇数节点和偶数节点分别排在一块儿。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。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