LeetCode – Odd Even Linked List (Java)
Problem
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.
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.
Analysis
This problem can be solved by using two pointers. We iterate over the link and move the two pointers.
Java Solution
public ListNode oddEvenList(ListNode head) { if(head == null) return head; ListNode result = head; ListNode p1 = head; ListNode p2 = head.next; ListNode connectNode = head.next; while(p1 != null && p2 != null){ ListNode t = p2.next; if(t == null) break; p1.next = p2.next; p1 = p1.next; p2.next = p1.next; p2 = p2.next; } p1.next = connectNode; return result; } |
<pre><code> String foo = "bar"; </code></pre>
-
shivam
-
Marina
-
Vandita
-
prasahnth
-
prashanth
-
Lekan Osagie
-
Rishabh Jain
-
Alina