leetcode 328. Odd Even Linked List

来源:互联网 发布:网络大专可以做人事吗 编辑:程序博客网 时间:2024/06/06 18:54

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



struct ListNode* oddEvenList(struct ListNode* head) {if (head == NULL)return NULL;struct ListNode*n, *n1, *pre,*head1;n = head; n1 = NULL; pre = NULL; head1 = NULL;int k = 1;while (n != NULL){if (k % 2 == 0){if (n1 == NULL){n1 = n;head1 = n;}else{n1->next = n;n1 = n1->next;}pre->next = n->next;n = n->next;}else{pre = n;n = n->next;}k++;}if (n1 != NULL)n1->next = NULL;pre->next = head1;return head;}

accepted


0 0