2014-05-03 23:18

题目链接

原题:

Insert a element in a sorted circular linked list

题目:题意简单明了,向一个有序的循环单向链表中插入元素,使得链表仍然有序。

解法:由于是循环链表,所以表尾指向表头。链表只能顺序访问,不额外添加数据的情况下就没法以对数的时间进行查找了。有几个边缘情况需要考虑:1. 链表为空 2. 插入到链表头 3. 插入到链表尾。考虑到各种可能情况,就能做出这题。

代码:

 // http://www.careercup.com/question?id=5735304249999360
struct ListNode {
int val;
ListNode *next;
ListNode(int _val = ): val(_val), next(nullptr) {};
}; class Solution {
void insertElement(ListNode *&head, int new_val) {
if (head == nullptr) {
head = new ListNode(new_val);
head->next = head;
return;
} ListNode *ptr = nullptr;
if (new_val <= head->val) {
ptr = new ListNode(head->val);
ptr->next = head->next;
head->next = ptr;
head->val = new_val;
} else {
ListNode *prev = head;
ListNode *ptr2 = head->next;
while (ptr2 != head && ptr2->val < new_val) {
prev = prev->next;
ptr2 = ptr2->next;
}
ptr = new ListNode(new_val);
ptr->next = ptr2;
prev->next = ptr;
}
};
};

最新文章

  1. JavaScript获取浏览器高度和宽度值(documentElement,clientHeight,offsetHeight,scrollHeight,scrollTop,offsetParent,offsetY,innerHeight)
  2. HttpCookie加匿名类实现多语言
  3. Java-httpClient警告: Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended.
  4. Unity3D 之连按移动加速
  5. curl测试puppet http api接口
  6. windows server 2012 iis8.0部署mvc报错
  7. 怎么用C#获取Scenario step在specflow里
  8. vim note
  9. Html.Partial(&quot;&quot;)与Html.RenderPartial(&quot;&quot;)区别
  10. C# DateTime结构的常用方法
  11. 在Freeplane中显示与隐藏层级图标
  12. 微信小程序--家庭记账本开发--06
  13. Java中PO、DO、TO、DTO、 VO、 BO、POJO 、DAO的概念
  14. jdk1.7/1.8 HashMap、ConcurrentHashMap详解
  15. ReentrantReadWriteLock 读写锁解析
  16. keil5 MDK warning:registered ARM compiler version not found in path
  17. javascript避免dom事件重复触发
  18. Android -- 面试 -- 数据库升级策略
  19. Client Dataset Basics
  20. go get中的...

热门文章

  1. Ajax 传统的异步登陆
  2. View的setOnClickListener的添加方法
  3. android 使用NinePatch图作Background,导致布局混乱
  4. CSS之简单树形菜单
  5. UI1_UIScrollView
  6. 【ASP.NET】获取网站目录的方法
  7. (转)RabbitMQ消息队列(六):使用主题进行消息分发
  8. JavaScript之Function函数深入总结
  9. arcgis js api 本地化配置
  10. 【风马一族_Android】造作app的效果图