LeetCode Odd Even Linked List

来源:互联网 发布:php代码混淆解密工具 编辑:程序博客网 时间:2024/05/18 00:17

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


0 0
原创粉丝点击