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

将奇数节点放在链表前面,这个奇数时数量,不是元素的值。并且也要相对位置也要按照原链表的相对位置。

1.如果节点个数大于等于三个才能进行相应的操作。如果不满足该条件,直接返回头指针。

2.指针p指向当前奇数节点的最后一个,q指向奇数节点链接的下一个节点。如上链表,p指向1的节点,q指向3。并且q需要一个前驱指针front,用来链接偶数节点。

3. 当1->3后,此时链表为1->3->2->4->5->NULL。由于下次p需要指向3节点,q需要指向5节点,因此在链接之前,先标记下一次q的前驱flag = q -> next,flag的下一个节点为下一次需要链接的奇数节点。此时flag指向4的节点。在链接完成后,p = q, front = flag,  q = front -> next。

注:当链表为1->2->3->NULL时,当完成奇数节点链接后,由于flag == NULL,再无奇数节点可以链接。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        if (head == NULL || head -> next == NULL || head -> next -> next == NULL) {
            return head;
        }
        ListNode* p = head, *q = head -> next -> next;
        ListNode* front = head -> next;
        ListNode* flag = NULL;
        while (q) {
            flag = q -> next;
            front -> next = q -> next;
            q -> next = p -> next;
            p -> next = q;
            if (flag == NULL) {
                return head;
            }
            p = q;
            front = flag;
            q = flag -> next;
        }
        return head;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值