leetcode Odd Even Linked List

leetcode 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 …

题目地址:leetcode Odd Even Linked List

题意:给定一个单向链表,要求你将所有奇数位置的节点“提”到前面,如

  • 1->2->3->4->5->NULL

变为

  • 1->3->5->2->4->NULL

思路:

很简单的,用两个指针即可,一个指针p指向当前遍历的奇数节点的最后一个位置,另一个指针q指向待提取的奇数节点的前一个位置。

然后把q.next 的节点删除,插入到p.next的位置即可

 

C++

 

Java

 

Python

 

 

本文是leetcode 328 Odd Even Linked List 的题解,更多题解可见 https://www.hrwhisper.me/leetcode-algorithm-solution/

本博客若无特殊说明则由 hrwhisper 原创发布
转载请点名出处:细语呢喃 > leetcode Odd Even Linked List
本文地址:https://www.hrwhisper.me/leetcode-odd-even-linked-list/

您的支持将鼓励我继续创作!

Leetcode , , , , . permalink.

One thought on “leetcode Odd Even Linked List

  1. Hi,
    thanks for posting a solution. It helped me finding my mistake. In essence, I put a p= head and q=head.next before while loop, and that was enough to give me a wrong solution.

Leave a Reply

Your email address will not be published. Required fields are marked *