【leetcode】328:奇偶链表

题目如下:

 

 这个题目的要求让我们在O(n) time内完成,空间复杂度为O(1),因此我们只能遍历一次,然后使用常数个变量,因此我们立马就会想到使用两个变量,一个用于保留奇数链表的指针,另一个用来保留偶数链表的指针,然后我们遍历整个head 链表,遇到奇数就将奇数指针往后移动,遇到偶数也分别往后移动一格。移动到head的tail后,偶数的tail最后用none收尾,不然会造成在进行测试用例测试的时候,链表扫描超时。我的方法速度超越了99%的人,代码如下:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def oddEvenList(self, head: ListNode) -> ListNode:
        ji_node=ListNode(0)
        ji=ji_node
        ou_node=ListNode(0)
        ou=ou_node
        i=0
        while head:
            if i%2==1:
                # this is ou
                ou_node.next=head
                ou_node=ou_node.next
                head=head.next
                i+=1
            else:
                ji_node.next=head
                ji_node=ji_node.next
                head=head.next
                i+=1
        ji_node.next=ou.next
        ou_node.next=None
        return ji.next

 

速度如下:

 

posted @ 2021-08-28 23:52  Geeksongs  阅读(33)  评论(0编辑  收藏  举报

Coded by Geeksongs on Linux

All rights reserved, no one is allowed to pirate or use the document for other purposes.