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