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


328 Odd Even Linked List

练手的two pointer操作
将linkedlist根据 基偶位置重新排布,不创造额外空间


1 -> 2 -> 3 -> 4 -> 5
p1 = node 1
p2 = node 2
当后面还有剩余的时候我们每次将值写进去一个位置,然后将p向后移动两个
逻辑很简单,但是对于linkedlist一定要熟练

class Solution(object):
    def oddEvenList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """

        if not head or not head.next:
            return head

        # now menas at least two elemnt in the array

        odd = head

        even = head.next

        otemp = odd
        etemp = even

        e1 = True
        e2 = True
        while e1 or e2:
            # print "this is odd"
            # print(odd)
            #
            # print "this is even"
            # print(even)
            if otemp.next and otemp.next.next:
                # if there is the next odd index node
                otemp.next = otemp.next.next
                otemp = otemp.next
            else:
                if otemp:
                    otemp.next = None
                e1 = False
            if etemp.next and etemp.next.next:
                # if there is the next even index node
                etemp.next = etemp.next.next
                etemp = etemp.next
            else:
                if etemp:
                    etemp.next = None
                e2 = False
        otemp.next =even
        print(odd)
        return odd

OJ上显示我速度beat 7% only,好奇..说明有更快的算法,估计是有更多的优化,因为我的算法处理even 和odd的重复,肯定有办法将其缩减到一个。。while.. too lazy...

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,775评论 0 33
  • Given a singly linked list, group all odd nodes together ...
    NapoleonY阅读 654评论 0 0
  • 成人思维,是现代化社会中人与人交流协作必备的基本素质。成人思维突出的表现就是平等沟通、相互尊重、找寻平衡点与利益接...
    傀儡宋饹馇阅读 317评论 0 0
  • 今天跟随罗及他的大家族一起去祭拜先人。一路荆棘,几个长辈拿着砍刀开路。一直是不喜爬山,但不知是否最近有锻炼或打球的...
    向向向上阅读 191评论 0 0
  • 依旧是那个盛夏 挥汗如雨 依稀的回忆 找不回去 站在异乡的原地 我看不清楚 怎么踏上征途 抛出难忘的幕幕 揉一把余...
    肃默阅读 127评论 0 8