题解 | #链表的奇偶重排#

链表的奇偶重排

https://www.nowcoder.com/practice/02bf49ea45cd486daa031614f9bd6fc3

<?php

/*class ListNode{
    var $val;
    var $next = NULL;
    function __construct($x){
        $this->val = $x;
    }
}*/

/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param head ListNode类 
 * @return ListNode类
 */
function oddEvenList( $head )
{
    if($head == null || $head->next == null || $head->next->next == null){
        return $head;
    }
    $oddHead = $head;
    $evenHead = $head->next;
    $oddPre = null;
    $odd = $head;
    $even = $head->next;
    while($even != null && $odd != null){
        $odd->next = $even->next;
        $oddPre = $odd;
        $odd = $odd->next;
        if($odd == null){
            break;
        }
        $even->next = $odd ->next;
        $even = $even->next;
    }
    if($even == null){
        $odd->next = $evenHead;
    }else{
        $oddPre->next = $evenHead;
    }
    return $oddHead;
}

空间O(1), 时间O(n)

使用奇偶数两个指针,一次遍历把链表分成奇数列和偶数列,之后连接。

全部评论

相关推荐

孙艹肘:校招不给三方直接让实习我都去了,,主打一个在学校呆着也是闲着,不如出来实习一下
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务