LeetCode 328. Odd Even Linked List

来源:互联网 发布:海文网络计划软件使用 编辑:程序博客网 时间:2024/06/06 19:43

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


解题思路是:
用两个指针分别指向第一个奇数节点和第一个偶数节点(要记录下第一个偶数节点),将奇数节点的后驱指向是偶数节点的后驱节点,偶数节点的后驱指向奇数节点的后驱节点,这样就形成了奇数节点链表和偶数节点链表,然后将奇数节点的后驱指向第一个节点。
public class Solution {    public ListNode oddEvenList(ListNode head) {        if(head==null){  //head为空            return head;        }        else if(head.next==null){  //只有一个节点            return head;        }        else{   //至少两个节点            ListNode p=head;            ListNode head2=head.next;            ListNode q=head2;            while(p.next!=null && q.next!=null){               // if(q.next!=null)   这条if语句可以加上                    p.next=q.next;                    p=p.next;                               //if(p.next!=null)   //这条if语句不能加,当原链表节点为奇数时,加上该if语句,会导致形成的偶数链表最后一个节点的next没有指向空                    q.next=p.next;                    q=q.next;                        }            p.next=head2;            return head;        }    }}

0 0