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.

解:給一個(gè)列表,所在列表位置為奇數(shù)為的節(jié)點(diǎn)放前面,偶數(shù)位的放后面。注意,奇偶之間要保持原來的順序。而且,不是值的奇偶,是位置即序號(hào)的奇偶。

思路:需要一個(gè)指針遍歷原列表curr,她的步長為2,一直指向偶數(shù)位,在跳躍之前把下一個(gè)節(jié)點(diǎn)給奇數(shù)位。


圖解.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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,855評論 0 10
  • 其實(shí)這并不是一個(gè)看臉的世界,那些人追的也不過是理想的情節(jié)和他故事,那些故事其實(shí)一直在你腦子里。長得美丑并不能用眼睛...
    山北的木閱讀 166評論 0 0
  • 文|源琪琪 青春是條河,誰不是摸石頭過河。 你錯(cuò)過了誰,誰又錯(cuò)過了你? 那些年 柯景騰如此努力只為了接近沈佳宜 只...
    源源de源琪琪閱讀 306評論 1 3
  • 快看到最后特別揪心,覺得喜劇怎么成了悲劇,不過劉軒和姍姍出現(xiàn)的時(shí)候,莫名地慶幸,覺得沒有遺憾。 ...
    Sofia蘇閱讀 186評論 0 0
  • 先來說兩個(gè)小實(shí)驗(yàn)。 實(shí)驗(yàn) (1): 實(shí)驗(yàn)者在NBA冠軍賽前一個(gè)星期,分別打電話給已經(jīng)買票和沒有買票的學(xué)生,問有票的...
    墨弦閱讀 596評論 1 3

友情鏈接更多精彩內(nèi)容