328. Odd Even Linked List
Example:
Given 1->2->3->4->5->NULL
,
return 1->3->5->2->4->NULL
.
//The program should run in O(1) space complexity and O(nodes) time complexity.
//Please note here we are talking about the node number and not the value in the nodes.
/** * 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 || !head->next ||!head->next->next) return head; ListNode * pWork = head; ListNode * end = head; int length = 1; while (end->next) { end = end->next; length++; } for (int i = 0; i < length/2; pWork = pWork->next,i++) { ListNode *tmp = pWork->next; pWork->next = tmp->next; end->next = tmp; tmp->next = NULL; end = tmp; } return head; } };