328. Odd Even Linked List
题目
原始地址:https://leetcode.com/problems/odd-even-linked-list/#/description
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode oddEvenList(ListNode head) {
}
}
描述
给定一个单链表,要求把所有奇数节点和偶数节点分开,并且奇数节点在前偶数节点在后,按照原来的相对顺序返回。
分析
题目很简单,新建两个链表头oddHead和evenHead,然后依次把节点分别放入即可。注意最后要把even的next置为null,否则可能会出现环的情况。
解法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode oddEvenList(ListNode head) {
ListNode oddHead = new ListNode(0), odd = oddHead, evenHead = new ListNode(0), even = evenHead, curr = head;
while(curr != null){
if(curr != odd.next){
odd.next = curr;
odd = odd.next;
} else {
even.next = curr;
even = even.next;
}
curr = curr.next;
}
odd.next = evenHead.next;
even.next = null;
return oddHead.next;
}
}