LeetCode Odd Even Linked List

来源:互联网 发布:js 给div添加右键事件 编辑:程序博客网 时间:2024/05/27 20:52

Description:

Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are 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.

Solution:

Keep track of one head node, and one tail node of odd and even index nodes respectively. Then merge these two.



public class Solution {public ListNode oddEvenList(ListNode head) {ListNode oddHead = null;ListNode oddTail = null;ListNode evenHead = null;ListNode evenTail = null;ListNode iter = head;ListNode next;int index = 0;while (iter != null) {index = 1 - index;if (index == 1) {if (oddHead == null) {oddHead = iter;oddTail = iter;} else {oddTail.next = iter;oddTail = iter;}} else {if (evenHead == null) {evenHead = iter;evenTail = iter;} else {evenTail.next = iter;evenTail = iter;}}next = iter.next;iter.next = null;iter = next;}if (oddTail != null)oddTail.next = evenHead;return oddHead;}}


0 0