List類題型: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:

Given1->2->3->4->5->NULL,

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

這道題雖然是Medium Level, 但是還是挺簡單的。

一開始做可能會有一個誤區, 先把Even node整一組, odd node整一組。 但是這么實踐一下,會發現本來的索引會被改變。 例如 1-->2-->3-->4-->5. ? ?1本來要靠2的索引找到3,但是現在2的索引變成了4,那1就到不了3了!?

List類問題做的時候最好畫一個Simple case: 例如1->2->3->4

很容易就會發現上述問題,所以解法應該是一個的while loop,?

一遍更改even, odd nodes的索引。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 我弟在學校又闖禍了。 原因是他邀約了幾個同學湊錢賣啤酒喝。 老媽在微信上和我抱怨跟我弟說什么他都不聽。 校長給我媽...
    西里個西閱讀 158評論 0 0
  • 一 、 在AppDelegate.h中設置導航欄 導入頭文件 ViewController.h 2 二、首先 我們...
    J_mine閱讀 1,121評論 0 0
  • 我來上海后,搬過幾次家,遇到過幾次奇葩的鄰居。有哭哭姑娘,有高跟鞋女郎,也有靈魂歌手……而自從搬到這里,生活才開始...
    趙七七o閱讀 424評論 0 2
  • 我堅持寫日記的第36天,我們的高級品酒師張錦全也準備每天堅持葡萄酒知識價值輸出365天! 并且他太太說,只要他堅持...
    莉莉說閱讀 386評論 0 0