【LeetCode】328. Odd Even Linked List

Problem:

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 ...

题目:将原链表奇数位移动到偶数位前,(注意不是节点值奇偶)原来奇偶序列中顺序不变。


思路:这个在循环中每次移动两位,第一位为奇数位,第二位为偶数位,分别放进奇偶链表指针末尾。


代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode oddEvenList(ListNode head) {
        if(head==null||head.next==null||head.next.next==null)
            return head;
        ListNode odd = head;
        ListNode even =head.next;
        ListNode cur = even;
        //head=head.next;
        ListNode node = head.next.next; 
        while(node!=null){
            odd.next=node;
            node = node.next;
            odd = odd.next;
            if(node==null)
                break;
            cur.next=node;
            node = node.next;
            cur=cur.next;
        }
        odd.next=even;
        cur.next=null;
        return head;
    }
}

猜你喜欢

转载自blog.csdn.net/hc1017/article/details/80196923