Java [Leetcode 328]odd even Linked List

Source: Internet
Author: User

Title Description:

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

Problem Solving Ideas:

Set two pointers, pointing to odd and even chains, traversing the entire data chain, or adding the number to an even chain if it is an odd position. Finally, the odd and even chains are connected.

The code is as follows:

/** * Definition for singly-linked list. * public class ListNode {*     int val; *     ListNode Next; *     listnode (int x) {val = x;}}} */public class Soluti On {public    ListNode oddevenlist (ListNode head) {        int i = 1;        ListNode cur = null, Oddhead = head, Evenhead = null, Oddcur = oddhead, evencur = null;        if (Oddhead = = null)        return head;        else {        evenhead = Oddhead.next;        Evencur = Evenhead;        }        if (Evenhead = = null)        return head;        cur = evencur.next;        while (cur! = null) {        if (i% 2 = = 1) {        oddcur.next = cur;        oddcur = cur;        cur = cur.next;        } else {        evencur.next = cur;        evencur = cur;        cur = cur.next;        }        i++;        }        Evencur.next = null;//of the last number of even chains is null, preventing the loop chain        oddcur.next = Evenhead;        return oddhead;}    }

  

Java [Leetcode 328]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.