LeetCode Odd Even Linked List

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;
	}
}


發佈了288 篇原創文章 · 獲贊 12 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章