45 lines
1.1 KiB
Java
45 lines
1.1 KiB
Java
/*
|
|
* @lc app=leetcode id=328 lang=java
|
|
*
|
|
* [328] Odd Even Linked List
|
|
*/
|
|
|
|
// @lc code=start
|
|
/**
|
|
* Definition for singly-linked list.
|
|
* public class ListNode {
|
|
* int val;
|
|
* ListNode next;
|
|
* ListNode() {}
|
|
* ListNode(int val) { this.val = val; }
|
|
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
|
|
* }
|
|
*/
|
|
class Solution {
|
|
public ListNode oddEvenList(ListNode head) {
|
|
if(head == null || head.next == null) {
|
|
return head;
|
|
}
|
|
ListNode oddDummy = new ListNode(0), oddTail = oddDummy, evenDummy = new ListNode(0), evenTail = evenDummy, cur = head;
|
|
int i = 1;
|
|
while(cur != null) {
|
|
if(i % 2 == 1) {
|
|
oddTail.next = cur;
|
|
cur = cur.next;
|
|
oddTail = oddTail.next;
|
|
oddTail.next = null;
|
|
} else {
|
|
evenTail.next = cur;
|
|
cur = cur.next;
|
|
evenTail = evenTail.next;
|
|
evenTail.next = null;
|
|
}
|
|
i++;
|
|
}
|
|
oddTail.next = evenDummy.next;
|
|
return oddDummy.next;
|
|
}
|
|
}
|
|
// @lc code=end
|
|
|