May 2009 - May 2017 论坛八周年-你的足迹,我的骄傲


一亩三分地论坛

 找回密码
 获取更多干活,快来注册

一亩三分地官方iOS手机应用下载
查看: 538|回复: 0
收起左侧

有关inserted node in circular list

[复制链接] |试试Instant~ |关注本帖
liuwz 发表于 2015-12-8 15:06:18 | 显示全部楼层 |阅读模式

2015(10-12月) 码农类 硕士 全职@Amazon - 网上海投 - 在线笔试 其他 |Otherfresh grad应届毕业生

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看,没有帐号?获取更多干活,快来注册

x
之前有发过贴提到C++里面返回一个new的pointer有runtime error,但是后来发现好像其他小伙伴都没有遇到这个问题,过些天video了怕被问,还请大家看看这code为啥会runtime error。。。(一模一样的思路,用JAVA写了一下,只是改了下语法就pass了所有的testcases...并不知道为啥)typedef struct CNode{
  int value;
  CNode* next;
}cnode;

cnode* insertednode(cnode* head, int target){
. from: 1point3acres.com/bbs   cnode* inserted = new cnode;. 1point 3acres 璁哄潧
  inserted->value = target; 鏉ユ簮涓浜.涓夊垎鍦拌鍧.
  inserted->next = NULL;

. from: 1point3acres.com/bbs   if(head == NULL){. 1point3acres.com/bbs
    return NULL;
  }

  if(head->next == head){ //only one node
    head->next = inserted;
    inserted->next = head;
    return inserted;
  }

  cnode* largest = head;
  cnode* smallest = head;
  cnode* tmp = head->next; 鏉ユ簮涓浜.涓夊垎鍦拌鍧.
  while(tmp != head){
      if(tmp->value > largest->value) largest = tmp;
      if(tmp->value < smallest->value) smallest = tmp;
      tmp = tmp->next;. 鐣欏鐢宠璁哄潧-涓浜╀笁鍒嗗湴
  }

  if(largest->value == smallest->value){ //all value are equal
    inserted->next = largest->next;.鏈枃鍘熷垱鑷1point3acres璁哄潧
    largest->next = inserted;
    return inserted;
  }. 1point3acres.com/bbs

  while(largest->value == largest->next->value){ //find last largest node(whose next is smallest node)
    largest = largest->next;
  }

  smallest = largest->next;

  if(target <= smallest->value || target >= largest->value){
    inserted->next = smallest;
    largest->next = inserted;. from: 1point3acres.com/bbs
    return inserted;
  }. From 1point 3acres bbs

  tmp = head;
  while(!(tmp->value <= target && tmp->next->value >= target)){
    tmp = tmp->next;.鏈枃鍘熷垱鑷1point3acres璁哄潧
  }

  inserted->next = tmp->next;
  tmp->next = inserted;
  return inserted;
}
代码比较繁琐,谢谢啦~



本版积分规则

关闭

一亩三分地推荐上一条 /5 下一条

手机版|小黑屋|一亩三分地论坛声明 ( 沪ICP备11015994号 )

custom counter

GMT+8, 2017-5-26 17:22

Powered by Discuz! X3

© 2001-2013 Comsenz Inc. Design By HUXTeam

快速回复 返回顶部 返回列表