328. Odd Even Linked List (python)

本文介绍了一种在单链表中将奇数位置节点与偶数位置节点分开并重新组合的方法,确保了原始顺序不变,同时实现了O(1)的空间复杂度和O(n)的时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
Example:
Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.
Note:
The relative order inside both the even and odd groups should remain as it was in the input.
The first node is considered odd, the second node even and so on …
题意:给一单链表,奇-偶-奇-偶-…..,不改变奇偶的原始顺序,输出奇-奇-偶-偶-……,不能改变结点的值,时间复杂度为o(n),空间复杂度为0(1)
思路:提取奇数链表和偶数链表,然后拼接即可
方法一:偶数链表新建一个头结点,主要是要注意最后一位是偶数还是奇数
Runtime: 112 ms
方法二:偶数链表需要设置头结点用于拼接,注意停止循环的条件,与方法一不同,
Runtime: 75 ms
方法二优于方法一

方法一:

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

class Solution(object):
    def oddEvenList(self, head):
        if not head or not head.next:
            return head
        p=head
        deven=ListNode(0)
        p1=deven
        while p.next and p.next.next:   
            p1.next=p.next
            p.next=p.next.next
            p=p.next
            p1=p1.next
        if p.next:
            p1.next=p.next
        else:
            p1.next=None
        p.next=deven.next
        return head    

方法二:

class Solution(object):
    def oddEvenList(self, head):
        if not head or not head.next:
            return head
        p1=head
        p2=evenhead=head.next
        while p2 and p2.next:   
            p1.next=p1.next.next
            p1=p1.next
            p2.next=p2.next.next
            p2=p2.next
        p1.next=evenhead
        return head    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值