Odd even Linked List
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we is 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 is in the input.
The first node is considered odd, the second node even ...
https://leetcode.com/problems/odd-even-linked-list/
It is required to rearrange the list according to the parity order of the subscript.
Traverse, open four pointers, two (Oddhead, evenhead) respectively pointing to the odd-numbered and even-numbered chain heads;
The other two (P, Q) points to the odd and even list elements currently being processed.
Finally, the odd and even lists are linked together.
1 /**2 * Definition for singly-linked list.3 * Function ListNode (val) {4 * This.val = val;5 * this.next = null;6 * }7 */8 /**9 * @param {listnode} headTen * @return {ListNode} One */ A varOddevenlist =function(head) { - if(Head = = =NULL|| Head.next = = =NULL)returnhead; - varOddhead =NewListNode ( -1), Evenhead =NewListNode (-1); the varp = oddhead, q = evenhead, isodd =true; - while(Head!==NULL){ - if(isodd) { -P.next =head; +p =P.next; -IsOdd =false; +}Else{ AQ.next =head; atQ =Q.next; -IsOdd =true; - } -Head =Head.next; - } -Q.next =NULL; inP.next =Evenhead.next; - returnOddhead.next; to};
[Leetcode] [JavaScript] Odd even Linked List