LeetCode:Odd Even Linked List

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:
Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.

Note:
The relative order inside both the even and odd groups should remain as it was in the input. 

The first node is considered odd, the second node even and so on ...

给出一个链表,要求将所有的奇数位置上的节点移动到链表的前面部分,将所有的偶数位置上的结点移动到链表的后面部分。两个部分的结点的相对顺序跟原来保持一致,并且空间复杂度必须为O(1),时间复杂度必须为O(n)。

解题思路:

使用两个指针,一个指向奇数位置结点,一个指向偶数位置上结点,并且记录下偶数位置上第一个结点,然后对链表进行遍历,最终形成两个链表,一个是奇数位置上的结点链表,一个是偶数位置上的结点链表,最后将奇数位置上的链表尾结点和一开始记录的偶数位置的链表头连接起来,即可完成。时间复杂度为O(n),空间复杂度为O(1),符合题目要求。


代码如下:

/**
 * 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) {
        if (head != null) {
    
        ListNode odd = head, even = head.next, evenHead = even; 
    
        while (even != null && even.next != null) {
            odd.next = odd.next.next; 
            even.next = even.next.next; 
            odd = odd.next;
            even = even.next;
        }
        odd.next = evenHead; 
    }
    return head;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章