LeetCode Problem: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 …



思路:

按照題意的意思是將給定鏈表的奇數(下標,從1開始)節點和偶數節點分開,奇數的節點在前面,偶數的在後面,返回新鏈的鏈頭指針。可以遍歷鏈表,當下一個(爲了能夠刪除節點,因此每次判斷是否需要移動的是下一個節點,而不是當前節點)節點是奇數節點,那麼就移到前面去,因此需要弄兩個指針,一個用於遍歷鏈表,一個用於指示插入節點的位置。注意在發生節點移動時遍歷指針並不需要使用p=p->next調到下一節點,因爲此時已經是指向下一個節點了。



AC代碼:

class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
    //插入點位置
    ListNode* point = head;
    //遍歷鏈表指針
    ListNode* p = head;
    ListNode* temp = NULL;
    int index = 1;
    while(p != NULL && p->next != NULL) {
        //實際移動的是下一節點
        if(index % 2 == 0) {
            temp = p->next;
            p->next = temp->next;
            temp->next = point->next;
            point->next = temp;

            point = temp;
        } else {
            p = p->next;
        }
        index++;
    }

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