"Linked list" Odd even Linked List

Source: Internet
Author: User

Topic:

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

Ideas:

This problem only takes the odd and even nodes out to form two linked lists, and then merges them.

/** Definition for singly-linked list. * Function ListNode (val) {* This.val = val; * This.next = null; *} 
    *//** * @param {listnode} head * @return {ListNode}*/varOddevenlist =function(head) {if(head==NULL|| head.next==NULL){        returnHead; }        varp=head.next.next,ohead=head,ehead=head.next,i=3,op=ohead,ep=Ehead;  while(p!=NULL){        if(i%2!=0) {Op.next=p; Op=Op.next; }Else{Ep.next=p; EP=Ep.next; } P=P.next; I++; } Ep.next=NULL; Op.next=Ehead; returnOhead;};

"Linked list" Odd even Linked List

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.