题目:
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.
Example 1:
Input: 1->2->3->4->5->NULL
Output: 2->3->6->7->1->5->4->NULL
此题需要将奇数编号结点放在一起,将偶数编号结点放在一起。可以将原链表分成奇数编号结点链表和偶数结点编号链表,最后将奇数编号结点链表尾结点指向偶数结点编号链表,即可解决问题。
public class OddEvenLinkedList {
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public ListNode oddEvenList(ListNode head) {
if (head == null || head.next == null || head.next.next == null)
return head;
ListNode evenHead = head.next;
ListNode cur = head;
ListNode node = evenHead;
while (cur.next != null && node.next != null) {
cur.next = cur.next.next;
node.next = node.next.next;
cur = cur.next;
node = node.next;
}
cur.next = evenHead;
return head;
}
}