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

給出一個鏈表,要求將所有的奇數位置上的節點移動到鏈表的前面部分,將所有的偶數位置上的結點移動到鏈表的後面部分。兩個部分的結點的相對順序跟原來保持一致,並且空間複雜度必須爲O(1),時間複雜度必須爲O(n)。

解題思路:

使用兩個指針,一個指向奇數位置結點,一個指向偶數位置上結點,並且記錄下偶數位置上第一個結點,然後對鏈表進行遍歷,最終形成兩個鏈表,一個是奇數位置上的結點鏈表,一個是偶數位置上的結點鏈表,最後將奇數位置上的鏈表尾結點和一開始記錄的偶數位置的鏈表頭連接起來,即可完成。時間複雜度爲O(n),空間複雜度爲O(1),符合題目要求。


代碼如下:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode oddEvenList(ListNode head) {
        if (head != null) {
    
        ListNode odd = head, even = head.next, evenHead = even; 
    
        while (even != null && even.next != null) {
            odd.next = odd.next.next; 
            even.next = even.next.next; 
            odd = odd.next;
            even = even.next;
        }
        odd.next = evenHead; 
    }
    return head;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章