|
| 1 | +/* |
| 2 | + * @lc app=leetcode id=328 lang=java |
| 3 | + * |
| 4 | + * [328] Odd Even Linked List |
| 5 | + * |
| 6 | + * https://leetcode.com/problems/odd-even-linked-list/description/ |
| 7 | + * |
| 8 | + * algorithms |
| 9 | + * Medium (48.16%) |
| 10 | + * Likes: 872 |
| 11 | + * Dislikes: 237 |
| 12 | + * Total Accepted: 162.4K |
| 13 | + * Total Submissions: 324K |
| 14 | + * Testcase Example: '[1,2,3,4,5]' |
| 15 | + * |
| 16 | + * Given a singly linked list, group all odd nodes together followed by the |
| 17 | + * even nodes. Please note here we are talking about the node number and not |
| 18 | + * the value in the nodes. |
| 19 | + * |
| 20 | + * You should try to do it in place. The program should run in O(1) space |
| 21 | + * complexity and O(nodes) time complexity. |
| 22 | + * |
| 23 | + * Example 1: |
| 24 | + * |
| 25 | + * |
| 26 | + * Input: 1->2->3->4->5->NULL |
| 27 | + * Output: 1->3->5->2->4->NULL |
| 28 | + * |
| 29 | + * |
| 30 | + * Example 2: |
| 31 | + * |
| 32 | + * |
| 33 | + * Input: 2->1->3->5->6->4->7->NULL |
| 34 | + * Output: 2->3->6->7->1->5->4->NULL |
| 35 | + * |
| 36 | + * |
| 37 | + * Note: |
| 38 | + * |
| 39 | + * |
| 40 | + * The relative order inside both the even and odd groups should remain as it |
| 41 | + * was in the input. |
| 42 | + * The first node is considered odd, the second node even and so on ... |
| 43 | + * |
| 44 | + * |
| 45 | + */ |
| 46 | +/** |
| 47 | + * Definition for singly-linked list. |
| 48 | + * public class ListNode { |
| 49 | + * int val; |
| 50 | + * ListNode next; |
| 51 | + * ListNode(int x) { val = x; } |
| 52 | + * } |
| 53 | + */ |
| 54 | +class Solution { |
| 55 | + public ListNode oddEvenList(ListNode head) { |
| 56 | + if (head == null || head.next == null) { |
| 57 | + return head; |
| 58 | + } |
| 59 | + |
| 60 | + ListNode odd = head; |
| 61 | + ListNode even = head.next; |
| 62 | + ListNode evenHead = head.next; |
| 63 | + |
| 64 | + while (even != null && even.next != null) { |
| 65 | + odd.next = odd.next.next; |
| 66 | + odd = odd.next; |
| 67 | + even.next = even.next.next; |
| 68 | + even = even.next; |
| 69 | + } |
| 70 | + |
| 71 | + odd.next = evenHead; |
| 72 | + |
| 73 | + return head; |
| 74 | + } |
| 75 | +} |
| 76 | + |
0 commit comments