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;
    }
};

你可能感兴趣的:(LeetCode,算法)