欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > cs106x-lecture14(Autumn 2017)-SPL实现

cs106x-lecture14(Autumn 2017)-SPL实现

2025/2/23 12:03:32 来源:https://blog.csdn.net/jm999999999/article/details/145803008  浏览:    关键词:cs106x-lecture14(Autumn 2017)-SPL实现

打卡cs106x(Autumn 2017)-lecture14

(以下皆使用SPL实现,非STL库,后续课程结束会使用STL实现)

1、min

Write a function named min that accepts a pointer to a ListNode representing the front of a linked list. Your function should return the minimum value in the linked list of integers. If the list is empty, you should throw a string exception.

Constraints: Do not construct any new ListNode objects in solving this problem (though you may create as many ListNode* pointer variables as you like). Do not use any auxiliary data structures to solve this problem (no array, vector, stack, queue, string, etc). Your function should not modify the linked list's state; the state of the list should remain constant with respect to your function.

Assume that you are using the ListNode structure as defined below:

解答:

int min(ListNode* front) {int m;if (front == nullptr) {throw std::string("");} else {m = front->data;ListNode* current = front;while (current->next != nullptr) {current = current->next;if (m > current->data) {m = current->data;}}}return m;
}

 

2、countDuplicates

Write a function named countDuplicates that accepts a pointer to a ListNode representing the front of a linked list. Your function should return the number of duplicates in a sorted list. Your code should assume that the list's elements will be in sorted order, so that all duplicates will be grouped together. For example, if a variable named front points to the front of the following sequence of values, the call of countDuplicates(front) should return 7 because there are 2 duplicates of 1, 1 duplicate of 3, 1 duplicate of 15, 2 duplicates of 23 and 1 duplicate of 40:

{1, 1, 1, 3, 3, 6, 9, 15, 15, 23, 23, 23, 40, 40}

Constraints: Do not construct any new ListNode objects in solving this problem (though you may create as many ListNode* pointer variables as you like). Do not use any auxiliary data structures to solve this problem (no array, vector, stack, queue, string, etc). Your function should not modify the linked list's state; the state of the list should remain constant with respect to your function. You should declare the function to indicate this to the caller.

Assume that you are using the ListNode structure as defined below:

解答:

int countDuplicates(ListNode* front) {int count = 0;if (front == nullptr) {return count;} else {ListNode* current = front;while (current->next != nullptr) {if (current->data == current->next->data) {count++;}current = current->next;}}return count;
}

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词