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

删除有序链表中重复的元素-I

http://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79

奇偶链表分别放,最后在合并

引入没用的结点充当头

注意:

  1. 20行、21行的oddList.next = null ; evenList.next=null必须要写,因为他们的next不为空
function oddEvenList( head ) {
  if(head==null || head.next==null)
    return head;
  
  let oddList = {}, savedOddList = oddList;;//奇数链表
  let evenList = {}, savedEvenList = evenList;;//偶数链表
  
  let flag = true;//true表示奇数个
  while(head != null){
    if(flag){
      oddList.next = head;
      oddList = oddList.next;
    }else{
      evenList.next = head;
      evenList = evenList.next;
    }
    head = head.next;
    flag = !flag;
  }
  oddList.next = null;
  evenList.next = null;//!!!!
  
  oddList.next = savedEvenList.next;
  return savedOddList.next;
}
module.exports = {
    oddEvenList : oddEvenList
};
全部评论

相关推荐

威猛的小饼干正在背八股:挂到根本不想整理
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务