328-Odd Even Linked List leecode

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

Credits:
Special thanks to @DjangoUnchained for adding this problem and creating all test cases.

解:给一个列表,所在列表位置为奇数为的节点放前面,偶数位的放后面。注意,奇偶之间要保持原来的顺序。而且,不是值的奇偶,是位置即序号的奇偶。

思路:需要一个指针遍历原列表curr,她的步长为2,一直指向偶数位,在跳跃之前把下一个节点给奇数位。


图解.jpg
class Solution(object):
    def oddEvenList(self, head):
      
       # :type head: ListNode
       # :rtype: ListNode
      
        if not head or not head.next:
            return head
        
        odd = head
        even = head.nextw
        curr = even
        while curr and curr.next:
            odd.next = curr.next
            odd = odd.next
            curr.next = curr.next.next
            curr = curr.next
            
        odd.next = even
        return head
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,505评论 0 10
  • 其实这并不是一个看脸的世界,那些人追的也不过是理想的情节和他故事,那些故事其实一直在你脑子里。长得美丑并不能用眼睛...
    山北的木阅读 152评论 0 0
  • 文|源琪琪 青春是条河,谁不是摸石头过河。 你错过了谁,谁又错过了你? 那些年 柯景腾如此努力只为了接近沈佳宜 只...
    源源de源琪琪阅读 282评论 1 3
  • 快看到最后特别揪心,觉得喜剧怎么成了悲剧,不过刘轩和姗姗出现的时候,莫名地庆幸,觉得没有遗憾。 ...
    Sofia苏阅读 173评论 0 0
  • 先来说两个小实验。 实验 (1): 实验者在NBA冠军赛前一个星期,分别打电话给已经买票和没有买票的学生,问有票的...
    墨弦阅读 547评论 1 3