[Leetcode] [JavaScript] Odd even Linked List

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.