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