【LeetCode】29.Linked List—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 1:

Input: 1->2->3->4->5->NULL
Output: 1->3->5->2->4->NULL

Example 2:

Input: 2->1->3->5->6->4->7->NULL
Output: 2->3->6->7->1->5->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 ..

    这里想到定义三个标签。两个滑动标签指针,一个固定标签指针。初始时,一个滑动标签指针指向链表头head,另一个滑动标签指针和固定标签指针指向第二个结点。因为当需要插入和删除一个结点时,需要用到该结点的前驱和后继,是这里定义三个标签指针的原因。固定标签指针始终指向初始状态链表的第二个结点,因为要在次结点前插入移动来的结点。两个滑动标签指针在插入完毕后相继向后滑动,进行下一轮移动操作。
    class Solution {
    public:
        ListNode* oddEvenList(ListNode* head) { 
            if(head==NULL) return NULL;
            ListNode*p = head; //第一个滑动标签指针指向头结点
            if(head->next==NULL) return head;
            ListNode*q = head->next; //固定标签指针始终指向第二个结点
            ListNode*tag= q;   //第二个滑动标签指针指向头结点
            while(tag!=NULL && tag->next!=NULL)
            {
                p->next=tag->next; //tag始终指向要移动结点的前驱
                tag->next=tag->next->next;
                p->next->next=q;
                tag=tag->next;
                p=p->next;
            }
            return head;
        }
    };

     

posted @ 2019-08-30 09:22  蓝天下的一棵草  阅读(110)  评论(0编辑  收藏  举报