【leetcode】328. Odd Even Linked List

来源:互联网 发布:网络诈骗防范常识电影 编辑:程序博客网 时间:2024/06/03 22:36

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.

var oddEvenList = function(head) {    if(head === null||head.next === null){        return head;    }    var flag = true;    var h1 = head;    var h2 = head.next;    var s2 = h2;    var temp = h2.next;    while(temp!==null){        if(flag){            h1.next = temp;            h1 = h1.next;        }else{            h2.next = temp;            h2=h2.next;        }        flag = !flag;        temp = temp.next;    }    h2.next=null    h1.next = s2;    return head;};

对于自己,要注意的点也是老问题,也就是处理[] 和[1]这种空指针的时候,开头很重要,还有一点中间出错的是 对于最后的节点,要额外赋值 null ,特别是偶数列的尾巴。,不然会出错不能够转化。另外flag要记得转。

0 0