328. Odd Even Linked List

来源:互联网 发布:qq空间psd源码 编辑:程序博客网 时间:2024/05/21 10:24

题目

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

Credits:

Special thanks to @DjangoUnchained for adding this problem and creating all test cases.


Subscribe to see which companies asked this question.

我的解答

/** * 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 l = head;        // l1、l2分别为偶链表的头、尾节点        ListNode l1 = null;        ListNode l2 = null;        // l3为前一奇节点        ListNode l3 = head;        head = (head == null) ? null :head.next;        int index = 2;        while(head != null){            ListNode next = head.next;            if(index % 2 == 0)                //第一个偶节点,更新l1、l2;后面只更新偶链表尾节点l2                if(index / 2 ==1)                    l1 = l2 = head;                else{                    l2 = head;                }            else{                // 将此奇节点插入上一奇节点后面,偶链表插入此奇节点后面,再把下一节点插入偶链表后面                l3.next = head;                head.next = l1;                l2.next = next;                l3 = head;            }            head = next;            index ++;        }        return l;    }}
分析:遍历一遍链表;保存偶链表的起始和终止节点,遇到新的奇节点就将其插入前一奇节点后面,再把偶链表插入此奇节点后面,同时把下一节点插入偶链表后面(两个地方解开链表,再把两个解开的地方拼接起来);当遇到偶节点时,更新偶链表的尾节点。

答案

/** * 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;            ListNode even = head.next;            ListNode evenHead = even;            // 偶节点不为null且它还有不为null的子(奇)节点时,更新奇、偶链表            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;    }}
分析:偶节点存在且其子(奇)节点存在时,才更新奇链表和偶链表;否则不更新;最后把偶链表插到奇链表后面;

难点:不容易发现这个规律(判断条件);


0 0
原创粉丝点击