Careercup - Google面试题 - 5735304249999360

2014-05-03 23:18

题目链接

原题:

Insert a element in a sorted circular linked list

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

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

代码:

 1 // http://www.careercup.com/question?id=5735304249999360

 2 struct ListNode {

 3     int val;

 4     ListNode *next;

 5     ListNode(int _val = 0): val(_val), next(nullptr) {};

 6 };

 7 

 8 class Solution {

 9     void insertElement(ListNode *&head, int new_val) {

10         if (head == nullptr) {

11             head = new ListNode(new_val);

12             head->next = head;

13             return;

14         }

15         

16         ListNode *ptr = nullptr;

17         if (new_val <= head->val) {

18             ptr = new ListNode(head->val);

19             ptr->next = head->next;

20             head->next = ptr;

21             head->val = new_val;

22         } else {

23             ListNode *prev = head;

24             ListNode *ptr2 = head->next;

25             while (ptr2 != head && ptr2->val < new_val) {

26                 prev = prev->next;

27                 ptr2 = ptr2->next;

28             }

29             ptr = new ListNode(new_val);

30             ptr->next = ptr2;

31             prev->next = ptr;

32         }

33     };

34 };

 

你可能感兴趣的:(Google)