leet328. Odd Even Linked List

题目:

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 ...

分析:

  1. 由于链表的单向性,为满足原址操作的要求,需要定义奇数链表尾部指针和偶数链表头部指针
  2. 不断在原链表中将奇数节点移动到所有偶数节点之前,当前节点之前节点数目不变,不改变待操作链表节点的奇偶

代码:

class Solution(object):
    def oddEvenList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not (head and head.next):
            return head
        odd = head
        even = head.next
        evenHead = even
        oddEnd = odd
        odd = even.next
        while odd:
            # print odd.val
            oddEnd.next = odd
            oddEnd = oddEnd.next
            even.next = even.next.next
            oddEnd.next = evenHead
            even = even.next
            if even:
                odd = even.next
            else:
                break
        return head

思考:

  1. 当原链表节点数小于3时,无需变换


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yzpwslc

您的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值