天天看點

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

題意:

就是将一個單連結清單中的坐标為奇數的節點按照原來的順序放到前面,将原來是偶數序的節點放到後面。并且都要求奇數和偶數序列的順序要保持不變。

題解:

我們可以按照設定兩個單連結清單,一個專門用于放置奇數節點,另一個用于放置偶數節點,最後隻要将這個奇數節點的末尾直接指向歐樹節點的頭節點即可,即可完成工作。

public class Solution 
{
    public static ListNode oddEvenList(ListNode head) 
    {
        if (head == null || head.next == null)
            return head;
        ListNode even_head = head.next;
        ListNode odd = head, even = even_head;
        while(even != null && even.next != null) 
        {
            odd.next = even.next;
            even.next = even.next.next;
            odd = odd.next;
            even = even.next;
        }
        odd.next = even_head;
        return head;
    }
}